我一直在网上阅读,一些地方说这是不可能的,一些地方说这是可能的,然后给出一个例子,另一些地方反驳这个例子,等等。
如何在JavaScript中声明一个2维数组?(假设这是可能的) 我如何访问它的成员?(myArray[0][1] or myArray[0,1]?)
我一直在网上阅读,一些地方说这是不可能的,一些地方说这是可能的,然后给出一个例子,另一些地方反驳这个例子,等等。
如何在JavaScript中声明一个2维数组?(假设这是可能的) 我如何访问它的成员?(myArray[0][1] or myArray[0,1]?)
当前回答
两行:
var a = [];
while(a.push([]) < 10);
它将生成一个长度为10的数组a,其中充满数组。 (Push将一个元素添加到数组中并返回新的长度)
其他回答
我的解决方案不会是最好的,但只是给出我的解决方案来创建用户定义的多维数组。
这个函数接受行和列,
function createArray(row,column) {
let arr = [];
for(var i=0; i<row; i++){
arr[i] = [Math.floor(Math.random() * (10))];
for(var j=0;j<column;j++){
arr[i][j]= [Math.floor(Math.random() * (20))];
}
}
return arr;
}
var arrVal = createArray(4, 5);
console.log(arrVal);
const arr = new Array(5).fill(new Array(5).fill(0));
console.log(arr);
如果数组的大小未知会发生什么?或者数组应该动态创建和填充?另一种解决方案,为我工作是使用类与静态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
要创建一个4x6数组,只需这样做
const x = [...new Array(6)].map(elem => new Array(4))
通常从一个空数组开始是一个很好的实践,而不是填充w个随机值。(你通常在1D中将数组声明为const x =[],所以在2D中最好以w为空开始。)
Array.from({length: rows}).map(e => new Array(columns));