javascript - 当我使用 console.log 矩阵时,为什么会有这三个 [0][0][0][0][0][0] ?
问题描述
好的,所以我只想简单解释一下为什么我的控制台中有三个 [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);
解决方案
因为你一直在使用同一个row
数组。row
只需在每个循环上创建一个新数组。
function zeroArray(m, n) {
let newArray = [];
for (let i = 0; i < m; i++) {
let row = []; // Create the row inside the loop, so on each iteration a new row is created
for (let j = 0; j < n; j++) {
row.push(0);
}
newArray.push(row);
}
return newArray;
}
let matrix = zeroArray(3, 2);
console.log(matrix);
推荐阅读
- httpclient - HttpClient 和 Polly 延迟 14 秒
- c# - 从 Web 应用程序中的第二个智能卡读卡器读取数据
- php - 从 ms word 复制过去到 WordPress 问题
- r - 如何减去列表中的连续数字
- python - Python 脚本未从终端运行 [添加到 PATH 后]
- android - RecyclerView 上的过滤器仅显示列表中的第一个值
- c++ - constexpr 构造函数无法满足要求,但仍然是 constexpr。为什么?
- node.js - 节点失败退出代码 1
- asp.net - 如何从后面的代码(aspx.vb)中获取 Id 到 .aspx 上的 Dim 变量
- vba - 日期的 MS Access 过滤导致错误 3075