如何创建一个 NxN 数组 JavaScript?



我正在尝试创建一个 2D 数组,如下所示,当给定整数 n 时,我正在使用嵌套的循环,我可以创建数组,但由于某种原因我不知道如何用 1 到 (n *n( 填充它。有什么建议吗?

1 2 3 4 5 6 7 8 9

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

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)

谢谢大家!修改并弄清楚了

下面是一个基本解决方案。它有助于在解决问题之前可视化问题。从第一行开始,在第一列上。您只想在列填充所有值后更改行。外部 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);

最新更新