Home > database >  why this javascript code generates same output
why this javascript code generates same output

Time:11-30

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]}`)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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]}`)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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]
  • Related