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

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


当前回答

如何创建空二维数组(一行)

Array.from(Array(2), () => new Array(4))

2和4分别是一维和二维。

我们使用了Array.from,它可以接受一个类似数组的参数和每个元素的可选映射。

Array.from(arrayLike[, mapFn[, thisArg]])

var arr = Array.from(Array(2), () => new Array(4)); Arr [0][0] = 'foo'; console.info (arr);

同样的技巧可以用于创建包含1…N的JavaScript数组


或者(但当n = 10,000时效率更低,为12%)

Array(2).fill(null).map(() => Array(4))

性能下降的原因是我们必须初始化第一个维度的值才能运行.map。记住,数组不会分配位置,直到你通过.fill或直接赋值对它进行排序。

var arr =阵列(2).fill (null) . map(() = >阵列(4)); Arr [0][0] = 'foo'; console.info (arr);


跟进

这里有一个方法看起来是正确的,但有问题。

 Array(2).fill(Array(4)); // BAD! Rows are copied by reference

虽然它确实返回了显然需要的二维数组([[<4空项>],[<4空项>]]),但有一个问题:一维数组是通过引用复制的。这意味着arr[0][0] = 'foo'实际上会改变两行而不是一行。

var arr =数组(2).fill(数组(4)); Arr [0][0] = 'foo'; console.info (arr); console.info (arr [0] [0], arr [1] [0]);

其他回答

对于一行程序爱好者来说

// 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"))

这将构造任何维度的数组。

function makeArrayChildren(parent, firstDimension, ...dimensions) {
  for (let i = 0; i < parent.length; i++) {
    parent[i] = new Array(firstDimension);
    if (dimensions.length != 0) {
      makeArrayChildren(parent[i], ...dimensions);
    }
  }
}
function makeArray(firstDimension, ...dimensions) {
  if (firstDimension == undefined) {
    throw Exception("Too few dimensions");
  }
  let topArray = new Array(firstDimension);
  if (dimensions.length != 0) makeArrayChildren(topArray, ...dimensions);
  return topArray;
}

这里还有另外两个我想做的函数,我可以用它作为一个完整性检查:一个用于在多维数组中所有最低级别项上执行的每个函数,一个填充方法。

Array.prototype.dimensionalFill = function (value) {
  for (let i = 0; i < this.length; i++) {
    const elem = this[i];
    if (elem instanceof Array) {
      elem.dimensionalFill(value);
    } else {
      this[i] = value;
    }
  }
};
/*Unlike forEach, this also loops over undefined values. */
Array.prototype.dimensionalForEach = function (callableFunc, thisArg) {
  if (thisArg != undefined) {
    return this.dimensionalForEach(callableFunc.bind(thisArg));
  }
  for (let i = 0; i < this.length; i++) {
    const elem = this[i];
    if (elem instanceof Array) {
      elem.dimensionalForEach(callableFunc);
    } else {
      callableFunc(elem, i, this);
    }
  }
};

这里有一个漂亮的小检查,它使用了所有的特性。所以至少,它不可能完全错误。

let arr = makeArray(10, 10, 5, 4);
arr.dimensionalFill(2);
let sum = 0;
arr.dimensionalForEach((elem) => {
  sum += elem;
});
console.log(`sum: ${sum} === ${10 * 10 * 5 * 4 * 2}`);

值得一提的是,在这一点上,创建一个全新的结构将是一个更好的实践,但这很有趣。

实际上呢?是的。你可以创建一个数组的数组,作为一个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]被转换为一个字符串,用作表对象的字符串键。