我一直在网上阅读,一些地方说这是不可能的,一些地方说这是可能的,然后给出一个例子,另一些地方反驳这个例子,等等。

如何在JavaScript中声明一个2维数组?(假设这是可能的) 我如何访问它的成员?(myArray[0][1] or myArray[0,1]?)


当前回答

对于一行程序爱好者来说

// creates 8x8 array filed with "0"    
const arr2d = Array.from({ length: 8 }, () => Array.from({ length: 8 }, () => "0"))

另一个(来自dmitry_romanov的评论)使用Array().fill()

// creates 8x8 array filed with "0"    
const arr2d = Array(8).fill(0).map(() => Array(8).fill("0"))

使用ES6+扩展操作符(“受InspiredJW启发”:))

// same as above just a little shorter
const arr2d = [...Array(8)].map(() => Array(8).fill("0"))

其他回答

我的方法与@Bineesh的答案非常相似,但采用了更普遍的方法。

你可以这样声明双数组:

var myDoubleArray = [[]];

并以以下方式存储和访问内容:

var testArray1 = [9,8]
var testArray2 = [3,5,7,9,10]
var testArray3 = {"test":123}
var index = 0;

myDoubleArray[index++] = testArray1;
myDoubleArray[index++] = testArray2;
myDoubleArray[index++] = testArray3;

console.log(myDoubleArray[0],myDoubleArray[1][3], myDoubleArray[2]['test'],) 

这将打印预期的输出

[ 9, 8 ] 9 123

我修改了Matthew Crumley关于创建多维数组函数的回答。我已经添加了要作为数组变量传递的数组的维度,还有另一个变量- value,它将用于设置多维数组中最后一个数组的元素的值。

/*
*   Function to create an n-dimensional array
*
*   @param array dimensions
*   @param any type value
*
*   @return array array
 */
function createArray(dimensions, value) {
    // Create new array
    var array = new Array(dimensions[0] || 0);
    var i = dimensions[0];

    // If dimensions array's length is bigger than 1
    // we start creating arrays in the array elements with recursions
    // to achieve multidimensional array
    if (dimensions.length > 1) {
        // Remove the first value from the array
        var args = Array.prototype.slice.call(dimensions, 1);
        // For each index in the created array create a new array with recursion
        while(i--) {
            array[dimensions[0]-1 - i] = createArray(args, value);
        }
    // If there is only one element left in the dimensions array
    // assign value to each of the new array's elements if value is set as param
    } else {
        if (typeof value !== 'undefined') {
            while(i--) {
                array[dimensions[0]-1 - i] = value;
            }
        }
    }

    return array;
}

createArray([]);              // [] or new Array()

createArray([2], 'empty');    // ['empty', 'empty']

createArray([3, 2], 0);       // [[0, 0],
                              //  [0, 0],
                              //  [0, 0]]

一个简单的例子:

var blocks = [];

blocks[0] = [];

blocks[0][0] = 7;
const arr = new Array(5).fill(new Array(5).fill(0));
console.log(arr);

我发现下面是最简单的方法:

Var array1 = [[]]; Array1 [0][100] = 5; alert (array1 [0] [100]); 警报(array1.length); alert (array1 [0] . length);