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

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


当前回答

如果数组的大小未知会发生什么?或者数组应该动态创建和填充?另一种解决方案,为我工作是使用类与静态2d数组变量,在数组中不存在索引的情况下将启动它:

function _a(x,y,val){
    // return depending on parameters
    switch(arguments.length){
        case 0: return _a.a;
        case 1: return _a.a[x];
        case 2: return _a.a[x][y];
    }

    // declare array if wasn't declared yet
    if(typeof _a.a[x] == 'undefined')
        _a.a[x] = [];

    _a.a[x][y] = val;
}
// declare static empty variable
_a.a = [];

语法将是:

_a(1,1,2); // populates [1][1] with value 2
_a(1,1);   // 2 or alternative syntax _a.a[1][1]
_a(1);     // [undefined × 1, 2]
_a.a;      // [undefined × 1, Array[2]]
_a.a.length

其他回答

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

使用数组推导式

在JavaScript 1.7及更高版本中,您可以使用数组推导式来创建二维数组。您还可以在填充数组时过滤和/或操作条目,而不必使用循环。

var rows = [1, 2, 3];
var cols = ["a", "b", "c", "d"];

var grid = [ for (r of rows) [ for (c of cols) r+c ] ];

/* 
         grid = [
            ["1a","1b","1c","1d"],
            ["2a","2b","2c","2d"],
            ["3a","3b","3c","3d"]
         ]
*/

您可以创建任何n x m的数组,并通过调用填充默认值

var default = 0;  // your 2d array will be filled with this value
var n_dim = 2;
var m_dim = 7; 

var arr = [ for (n of Array(n_dim)) [ for (m of Array(m_dim) default ]] 
/* 
         arr = [
            [0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0],
         ]
*/

更多示例和文档可以在这里找到。

请注意,这还不是一个标准功能。

如果数组的大小未知会发生什么?或者数组应该动态创建和填充?另一种解决方案,为我工作是使用类与静态2d数组变量,在数组中不存在索引的情况下将启动它:

function _a(x,y,val){
    // return depending on parameters
    switch(arguments.length){
        case 0: return _a.a;
        case 1: return _a.a[x];
        case 2: return _a.a[x][y];
    }

    // declare array if wasn't declared yet
    if(typeof _a.a[x] == 'undefined')
        _a.a[x] = [];

    _a.a[x][y] = val;
}
// declare static empty variable
_a.a = [];

语法将是:

_a(1,1,2); // populates [1][1] with value 2
_a(1,1);   // 2 or alternative syntax _a.a[1][1]
_a(1);     // [undefined × 1, 2]
_a.a;      // [undefined × 1, Array[2]]
_a.a.length

nodejs + lodash版本:

var _ = require("lodash");
var result = _.chunk(['a', 'b', 'c', 'd', 'e', 'f'], 2);
console.log(result);
console.log(result[2][0]);

输出:

[ [ 'a', 'b' ], [ 'c', 'd' ], [ 'e', 'f' ] ]
e

您可以分配一个行数组,其中每一行都是相同长度的数组。或者你也可以用rows*columns元素分配一个一维数组,并定义方法将行/列坐标映射到元素索引。

无论选择哪种实现,如果将其包装在对象中,则可以在原型中定义访问器方法,从而使API易于使用。