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

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


当前回答

我发现这段代码适合我:

var map = [
    []
];

mapWidth = 50;
mapHeight = 50;
fillEmptyMap(map, mapWidth, mapHeight);

...

function fillEmptyMap(array, width, height) {
    for (var x = 0; x < width; x++) {
        array[x] = [];
        for (var y = 0; y < height; y++) {

            array[x][y] = [0];
        }
    }
}

其他回答

我不确定是否有人回答过这个问题,但我发现这对我很有效

var array = [[,],[,]]

eg:

var a = [[1,2],[3,4]]

例如,对于一个二维数组。

实际上呢?是的。你可以创建一个数组的数组,作为一个2D数组,因为每个项目本身就是一个数组: Let items = [ (1、2), (3、4), (5、6) ]; console.log(项目[0][0]);/ / 1 console.log(项目[0][1]);/ / 2 console.log(项目[1][0]);/ / 3 console.log(项目[1][1]);/ / 4 console.log(项目);

但从技术上讲,这只是一个数组的数组,而不是一个“真正的”2D数组,正如I. J. Kennedy指出的那样。

需要注意的是,您可以将数组嵌套到另一个数组中,从而创建“多维”数组。

我修改了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]]

还有另一种解决方案,它不强迫你预先定义2d数组的大小,而且非常简洁。

Var表= {} table[[1,2]] = 3 //注意双[[and]] Console.log (table[[1,2]]) // -> 3 .单击“确定”

这是因为,[1,2]被转换为一个字符串,用作表对象的字符串键。

二维数组的创建方式与一维数组相同。你像数组[0][1]一样访问它们。

var arr = [1, 2, [3, 4], 5];

alert (arr[2][1]); //alerts "4"