【发布时间】:2021-01-03 15:51:47
【问题描述】:
好的,所以我只想简单解释一下为什么我的控制台中有三个 [0][0][0][0][0][0] 在一个更大的数组中,而不仅仅是一个?我的问题可能与嵌套的 for 循环有关,所以如果你们能准确解释这里发生的事情,我将不胜感激。
function zeroArray(m, n) {
// Creates a 2-D array with m rows and n columns of zeroes
let newArray = [];
let row = [];
for (let i = 0; i < m; i++) {
// Adds the m-th row into newArray
for (let j = 0; j < n; j++) {
// Pushes n zeroes into the current row to create the columns
row.push(0);
}
// Pushes the current row, which now has n zeroes in it, to the array
newArray.push(row);
}
return newArray;
}
let matrix = zeroArray(3, 2);
console.log(matrix);
【问题讨论】:
-
将 let row = ... 下移一行,到循环的内部。
-
您没有意识到的是您只有一个子数组,并且将同一数组的引用多次推送到外部数组中。尝试
matrix[0][0] = 1会看到所有子数组都获得该值,因为它们实际上是同一个数组对象的实例 -
嗨,我的回答怎么样?
标签: javascript console.log nested-for-loop