let day = [];
let hours = [];
for (let j = 0; j < 3; j++) {
for (let k = 0; k < 3; k++) {
hours[k] = Math.floor(Math.random() * 25 + 20);
}
day[j] = hours;
console.log(`day[${j}] ${day[j]}`);
}
console.log(`${day[0]}`)
console.log(`${day[1]}`)
console.log(`${day[2]}`)
2 Answers
When you declare let hours = []; globally, along with telling JavaScript that day[j] = hours;, day[j] will be assigned with the memory location of the global hours. In order to avoid that, you can assign new memory location for each hours generated by declaring it in block scope.
let day = [];
for (let j = 0; j < 3; j++) {
let hours = [];
for (let k = 0; k < 3; k++) {
hours[k] = Math.floor(Math.random() * 25 + 20);
}
day[j] = hours;
console.log(`day[${j}] ${day[j]}`);
}
console.log(`${day[0]}`)
console.log(`${day[1]}`)
console.log(`${day[2]}`)
Comments
As per day[j] = hours line, all the values of day i.e. day[0], day[1] and day[2] are referring to array hours.
In the last execution cycle of inner for loop, value of hours is set to [29,27,42]. Hence the output is same for all day values.
To have proper values for each day elements, modify the code as follows:
day[j] = [...hours]
day[j] = hours;This will only set the reference not the copy of hours array.