dimanche 13 décembre 2020

Javascript - Math.random inside nested loop returns same sequence every time

I'm trying to randomize values inside inside a nested loop:

let bools = {
  first: true,
  second: true,
  third: true,
  fourth: true,
  fifth: true,
};

results = [];
for (let i = 0; i < 3; i++) {
  for (let k in bools) {
    bools[k] = Math.random() > 0.5;
    console.log(bools[k]);
  }
  results.push({ i, bools });
}
console.log(results);

The results are the same sequence for each iteration of i. I was confused by this and tried a performance timestamp instead of a random number:

bools[k] = now() // from performance-now node package

and it returned the same precision timestamp sequence for each iteration also. What this tells me is the inner loop is running only once. Why not every iteration of the outer for loop? How can I get around this? Thx :)




Aucun commentaire:

Enregistrer un commentaire