1

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

VLAZ
  • 18,437
  • 8
  • 35
  • 54
Nick Carbone
  • 99
  • 1
  • 6
  • 1
    You only manipulate a single object called `bools` and insert it several times in `result`. – VLAZ Dec 13 '20 at 15:17
  • I see that you have used `results.push({ i, bools });`. What are you expecting from this? I have no idea if that is actually something. Would something like `results.push({ i: bools });` work better? Or do the two do the same thing? – Rojo Dec 13 '20 at 15:18
  • 1
    @Rojo it's still *the same object* inserted in several slots – VLAZ Dec 13 '20 at 15:19
  • @Rojo https://stackoverflow.com/questions/34414766/javascript-object-literal-what-exactly-is-a-b-c – Bergi Dec 13 '20 at 15:20

1 Answers1

2

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

Monsieur Merso
  • 356
  • 2
  • 7