0

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]}`)

1
  • 1
    day[j] = hours; This will only set the reference not the copy of hours array. Commented Nov 30, 2021 at 5:33

2 Answers 2

1

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]}`)

Sign up to request clarification or add additional context in comments.

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.