3 回答
TA贡献1719条经验 获得超6个赞
下面是一个基本的解决方案。它有助于在解决问题之前将问题形象化。您从第一行的第一列开始。您只希望在列填充所有值后更改行。外部 for 循环控制行,内部 for 循环控制列。
var n = 3;
var counter = 1;
var outerArray = [];
// Now just add to the array with a nested for loop
for(var i = 0; i < n; i++) {
// Add empty array to the outer array.
outerArray.push([]);
// outer for loop steps through the rows
for(var j = 0; j < n; j++) {
// The inner loop steps through the columns
outerArray[i][j] = counter;
counter++;
}
}
// Now just print the array.
console.log(outerArray);
TA贡献1824条经验 获得超5个赞
let n = 3, i, j;
let a = [];
for (i = 0; i < n; i ++) {
a[i] = [];
for (j = 0; j < n; j ++) {
a[i][j] = 1;
}
}
console.log(a);
TA贡献1828条经验 获得超3个赞
function printTable(n) {
let i, j;
let a = [];
let counter = 0;
for (i = 0; i < n; i ++) {
a[i] = [];
for (j = 0; j < n; j ++) {
counter++
a[i][j] = counter;
}
}
console.log(a);
}
printTable(4)
谢谢你们!修改了一下,搞明白了
添加回答
举报