1

My code:

function zeroArray() {
  let newArray = [];
  let row = [];
  for (let i = 0; i < 3; i++) {
    for (let j = 0; j < 2; j++) {
      row.push(0);
    }
        newArray.push(row);
  }
  return newArray
}

console.log(zeroArray())

From my perspective, its look like the result will be :

[[ 0, 0 ],[ 0, 0, 0, 0 ],[ 0, 0, 0, 0, 0, 0 ]]

but when the code run in the console it shows this, why is that?

[ [ 0, 0, 0, 0, 0, 0 ],[ 0, 0, 0, 0, 0, 0 ],[ 0, 0, 0, 0, 0, 0 ] ]
halfer
  • 19,824
  • 17
  • 99
  • 186
  • 2
    You push *the same* array multiple times. It's not *copies* but literally references to the same `row` array multiple times inside `newArray`. – VLAZ Feb 02 '20 at 19:04

2 Answers2

1
function zeroArray() {
  let newArray = [];
  let row = [];
  for (let i = 0; i < 3; i++) {
    for (let j = 0; j < 2; j++) {
      row.push(0);
    }
    newArray.push(row); // <== Problematic line
  }
  return newArray;
}

The problem is when you push row array into newArray, it doesn't actually push the values into it; it pushes the pointer to that array, which means after updating row array, if you push it again, it will push the same value to newArray.

Posted the illustration for detailed explanation:

enter image description here

The solution is as some other people noted, re-creating the array each time instead of using the same variable. For example, the solution could be:

function zeroArray() {
  const newArray = [];
  for (let i = 0; i < 3; i++) {
    const row = [];
    for (let j = 0; j < 2; j++) {
      row.push(0);
    }
    newArray.push(row); // <== Problematic line
  }
  return newArray;
}
technophyle
  • 7,972
  • 6
  • 29
  • 50
0

Looks like an unexpected instance of mutating an object. In this case, you're pushing the same row multiple times, then updating it (resulting in that it updates the three instances of it that end up in newArray). If you instead use something like newArray.push(row.slice()), the output will be as you expect.

Kamen Minkov
  • 3,324
  • 1
  • 14
  • 21