Nick Carbone
Nick Carbone

Reputation: 505

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 :)

Upvotes: 1

Views: 245

Answers (1)

Monsieur Merso
Monsieur Merso

Reputation: 2146

Try to replace:

 results.push({ i, bools });

with:

    results.push({ i, bools: Object.assign({}, bools) });

You keep referencing the same object 'bools' and constantly overriding it, so in the end you'll see result of the last iteration in every elemen of the 'results' array. On the other side 'Object.assign({}, bools) creates new object every time from the 'bools' reference. Read about it here

Upvotes: 2

Related Questions