0

I want to change the index of newAr on each click and console log the values of next object in newAr showed in looper function

Note: I only want the index second object values on second click and third object values in newAr on third click

HTML only has a button nothing else

const button = document.querySelector("button");

let firstVar = () => {
  const firstVarVariable = Math.round(Math.random() * 10);
  if (firstVarVariable < 5) {
    return true;
  } else {
    return false;
  }
};
let secondVar = () => {
  const firstVarVariable = Math.round(Math.random() * 10);
  if (firstVarVariable < 5) {
    return true;
  } else {
    return false;
  }
};
let thirdVar = () => {
  const firstVarVariable = Math.round(Math.random() * 10);
  if (firstVarVariable < 5) {
    return true;
  } else {
    return false;
  }
};

const newAr = [];
const pusher = () => {
  newAr.push({
    one: firstVar(),
    two: secondVar(),
    three: thirdVar(),
  });
  console.log(newAr);
  looper();
};

const looper = () => {
  for (const value of newAr) {
    console.log(value.one);
    console.log(value.two);
    console.log(value.three);
  }
  // I want to change the index of newAr array on click
  // Like i want to console log first object in array on first click
  // and second object on other click and third object
  // alsp please tell me if i can change some approch
};

button.addEventListener("click", () => {
  pusher();
});

1 Answer 1

2

let randomBool = () => Math.random() < 0.5;
// all three functions did the same thing...

const newAr = [];
const pusher = () => {
  newAr.push({
    one: randomBool(),
    two: randomBool(),
    three: randomBool(),
  });
  console.log(newAr);
  looper();
};

let index = 0; // counter / array index

const looper = () => {
  let value = newAr[index++]; // always getting the next element (starting from 0).
  
  console.log(value.one);
  console.log(value.two);
  console.log(value.three);
};

/***/
const button = document.querySelector("button");

button.addEventListener("click", () => {
  pusher();
});
<button>Test</button>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much It finally helped i was stuck on some issue in my code from 2 days.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.