Code Centrix
Code Centrix

Reputation: 39

Looping array on click in javascript

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();
});

Upvotes: 0

Views: 51

Answers (1)

OPTIMUS PRIME
OPTIMUS PRIME

Reputation: 1325

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>

Upvotes: 2

Related Questions