Answer the question
In order to leave comments, you need to log in
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);
Answer the question
In order to leave comments, you need to log in
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); //
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 questionAsk a Question
731 491 924 answers to any question