2.6 KiB
2.6 KiB
id, challengeType, forumTopicId, localeTitle
id | challengeType | forumTopicId | localeTitle |
---|---|---|---|
587d7b86367417b2b2512b3c | 1 | 301194 | 重新初始化循环中的变量时要小心 |
Description
console.log()
在每个循环中打印变量值可以发现与重置相关的错误或者重置变量失败。
Instructions
m
行和n
列“零”的二维数组。不幸的是,它没有产生预期的输出,因为row
变量没有在外部循环中重新初始化(设置回空数组)。修改代码,使其正确地返回包含 3 行 2 列“零”的二维数组,即[[0, 0], [0, 0], [0, 0]]
。
Tests
tests:
- text: 你应将变量<code>matrix</code>设置为 3 行 2 列“零”的二维数组。
testString: assert(JSON.stringify(matrix) == "[[0,0],[0,0],[0,0]]");
- text: 变量<code>matrix</code>应有 3 行。
testString: assert(matrix.length == 3);
- text: 变量<code>matrix</code>每行应有 2 列。
testString: assert(matrix[0].length == 2 && matrix[1].length === 2 && matrix[2].length === 2);
Challenge Seed
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);
Solution
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);