JavaScript 中创建二维数组的方法有:直接创建二维数组(使用数组字面量语法)使用 Array.from() 方法从一维数组创建使用 for 循环和 push() 方法手动创建

JavaScript 中如何创建二维数组
直接创建
最简单的创建二维数组的方法是使用数组字面量语法:
<code class="javascript">const myArray = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ];</code>
使用 Array.from()
要从一维数组创建二维数组,可以使用 Array.from() 方法:
<code class="javascript">const myArray = Array.from(Array(3), () => new Array(3));</code>
生成的数组将包含三个内层数组,每个内层数组包含三个元素。
使用 for 循环
还可以使用 for 循环和 push() 方法手动创建二维数组:
<code class="javascript">const myArray = [];
for (let i = 0; i < 3; i++) {
myArray[i] = [];
for (let j = 0; j < 3; j++) {
myArray[i].push(i * 3 + j);
}
}</code>示例
使用上述方法创建的二维数组示例:
<code class="javascript">// 使用数组字面量语法
const myArray1 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
// 使用 Array.from()
const myArray2 = Array.from(Array(3), () => new Array(3));
// 使用 for 循环
const myArray3 = [];
for (let i = 0; i < 3; i++) {
myArray3[i] = [];
for (let j = 0; j < 3; j++) {
myArray3[i].push(i * 3 + j);
}
}
console.log(myArray1); // 输出:[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
console.log(myArray2); // 输出:[[], [], []]
console.log(myArray3); // 输出:[[0, 1, 2], [3, 4, 5], [6, 7, 8]]</code>










