这个嵌套循环是如何得到这个输出的



很长一段时间以来,我一直在努力理解这个嵌套循环的输出。我真的很想了解它的作用。

我希望它输出:[ [ 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ] ]

但实际输出为:[ [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ] ]

在第一个内循环之后,row包含两个0,并且应该被推送到外循环中的newArray。看起来这并没有发生,我不明白为什么。第一个元素应该是[0, 0],对吧?。

我真的希望有人能明白我在这里的意思,并解释发生了什么!非常感谢。

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);

row传递给循环的所有迭代。为了实现您想要的,行在循环的每次迭代中都必须是唯一的,所以您需要在第一个循环中移动它。

为了更好地理解这个问题,请阅读更多关于JavaScript中的值和引用:https://www.javascripttutorial.net/javascript-pass-by-value/#:~:text=JavaScript%20pass%2Dby%2Dvalue%20或%20pass%4Dby%2Reference&text=It%20表示%20hat%20JavaScript%20副本,%20在%20函数的%20之外的变量%20。

function zeroArray(m, n) {
// Creates a 2-D array with m rows and n columns of zeroes

let newArray = [];
for (let i = 0; i < m; i++) {
let row = [];

// 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);
// Update n to get desired pattern
n += 2
}
return newArray;
}
let matrix = zeroArray(3, 2);
console.log(matrix);

这是因为JavaScript对象(和数组(只是内存中的一个引用。因此,您正在创建一个在内存中共享相同地址的数组数组,因为它们共享相同的地址,所以当您更新它(array.prototype.prush(时,您正在更新所有数组。解决方案是在第一个循环中创建一个新行:

function zeroArray(m, n) {  
const newArray = [];
for (let i = 0; i < m; i++) {
// If this isn't the first run, take the last value of row
const prevRow = i > 0 ? newArray[i-1] : [];
const row = [...prevRow]; // By using the spread operator(...), you can copy an array
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);

重要提示

这不是一种自然的JavaScript编写方式,您可以使用实现同样的效果

const zeroArray = (m, n) => Array.from({ length : m }).map((value, index) => {
return Array.from({ length : (index + 1) * n }).map(() => 0);
});

最新更新