javascript - 努力理解这个多层 for 循环是如何工作的
问题描述
问题
以下函数应该创建一个具有 m 行和 n 列零的二维数组。
回答
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);
我的问题
我熟悉在 for 循环内有一个 for 循环,以遍历数组的第二层。但在这个例子中,它似乎特别令人困惑。
请你一步一步解释这里发生了什么。
解决方案
实际上,此代码不起作用。如果你运行它,你会看到它创建了一个 3x6 而不是 6x3 的数组。
试试这个
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);
}
return newArray;
}
let matrix = zeroArray(3, 2);
console.log(matrix);
您需要在推送后重新初始化该行,或者,甚至更好
function zeroArray(m, n) {
// Creates a 2-D array with m rows and n columns of zeroes
let newArray = [];
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);
}
for (let i = 0; i < m; i++) {
// 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);
不要重新做初始化行的工作,因为所有的行都是一样的
推荐阅读
- c - 递归和遍历二叉树
- php - 如何获取在 Wordpress 帖子中上传的文件的附件 ID?
- angular - @output 在 Angular 10 中没有发出结果
- c++ - C++ 手动展开(条件和)比常规代码慢,期待 AVX 矢量化
- java - FileReader “吃掉”每个首字母
- c# - 使用值和键对 C# 映射进行排序
- python - 如何通过其他python脚本附加列表?
- authentication - RShiny、shinymanager、RSQLite、Heroku 部署
- dpdk - dpdk 如何禁用“CRC strip”、“header split”、“IP checksum offload”和“jumbo frame support”
- python - 在 matplotlib 中使用 TextArea 和 AnnotationBbox 绘制文本