# 快速、高效地创建 JavaScript 二维数组的方法

## 方法1: 使用双重循环创建二维数组

``````function createArray(rows, cols) {
var arr = new Array(rows);
for (var i = 0; i < rows; i++) {
arr[i] = new Array(cols);
for (var j = 0; j < cols; j++) {
arr[i][j] = 0;
}
}
return arr;
}
// 创建一个3x3的二维数组
var myArray = createArray(3, 3);
// 打印二维数组
console.log(myArray);``````

## 方法2: 使用 Array.from() 创建二维数组

ES6 的 Array.from() 方法提供了一种更高效的方法来创建二维数组。以下是一个示例代码：

``````function createArray(rows, cols) {
return Array.from({ length: rows }, () => new Array(cols).fill(0));
}
// 创建一个3x3的二维数组
var myArray = createArray(3, 3);
// 打印二维数组
console.log(myArray);``````

``````function createArray(x, y) {
let result = [];
for (let i = 0; i < x; i++) {
result[i] = [];
for (let j = 0; j < y; j++) {
result[i][j] = i * y + j + 1;
}
}
return result;
}
console.log("createArray(10, 10) = ", createArray(10, 10));``````

``````function createArray(x, y) {
return Array.from({ length: x }, (_, i) =>
Array.from({ length: y }, (_, j) => j + i * y + 1)
);
}
console.log("createArray(10, 10) = ", createArray(10, 10));``````

``````function createArray(x, y) {
let count = 1;
return Array.from({ length: x }, () =>
Array.from({ length: y }, () => count++)
);
}
console.log("createArray(10, 10) = ", createArray(10, 10));``````

``````function createArray(x, y) {
let count = 1;
return Array(x).fill().map(() => Array(y).fill().map(() => count++));
}
console.log("createArray(10, 10) = ", createArray(10, 10));``````

0 声望
0 粉丝
0 条评论