O
O
origami10242020-05-09 02:48:57
JavaScript
origami1024, 2020-05-09 02:48:57

Why the confusion in arrays?

let newArray = [];
let row = [];
for (let i = 0; i < 3; i++) {
    for (let j = 0; j < 2; j++) {
      row.push(0);
    }
    console.log(row)//видим, что сначала 2 элемента, потом 4, потом 6
    newArray.push(row);
  }
console.log(newArray);

It turns
out [ [ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ] ]

and not


Why?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Neverov, 2020-05-09
@origami1024

Because the row array is passed by reference to the newArray array, that is, each time you write newArray.push(row), you do not fix the current state of row in newArray, but make a reference to the same row variable, which you change later .
To test this thesis, you can run, for example, the following code:

let a = [1, 2];
let b = [a, a];
console.log(b); // 
a.push(3); // теперь изменим a и окажется
console.log(b); // 

If you want the newArray keys to have three different states of the row array, use the slice function for example:
let newArray = [];
let row = [];
for (let i = 0; i < 3; i++) {
    for (let j = 0; j < 2; j++) {
      row.push(0);
    }
    console.log(row)//видим, что сначала 2 элемента, потом 4, потом 6
    newArray.push(row.slice()); // функция slice() без аргументов возвращает копию массива, на котором применена
  }
console.log(newArray);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question