我需要做的是:
var a = [[[]]];
a[1][2][3] = "hello!"; // [...[undefined,undefined,undefined,"hello!"]...];
a[1][2][1] = "a"; // [...[undefined,"a",undefined,"hello!"]...]
a[2][3][4] = "new_index" // [...[undefined,"a",undefined,"hello!"]...[undefinedx4, "new_index"]]
就我而言,我不喜欢在指定索引之前实例化数组的大小,并在较大索引需要时增加大小。 由于js对多维数组的支持很弱,因此在javascript中执行此操作的最简单或最干净的方法是什么?
最佳答案
在 JS 中,数组是引用类型,因此创建 ND 数组很棘手。克隆工具会非常方便。因此,您可以执行以下操作;
Array.prototype.clone = function(){
return this.map(e => Array.isArray(e) ? e.clone() : e);
};
function arrayND(...n){
return n.reduceRight((p,c) => c = (new Array(c)).fill().map(e => Array.isArray(p) ? p.clone() : p ));
}
var arr = arrayND (2,3,4,"x")
console.log(JSON.stringify(arr));
初始参数定义尺寸,最后一个参数是填充值。
这应该可以在 ES6 之前兼容的浏览器上正常工作;
Array.prototype.clone = function(){
return this.map(function(e){
return Array.isArray(e) ? e.clone() : e;
});
};
function arrayND(){
var n = Array.prototype.slice.call(arguments);
return n.reduceRight(function(p,c){
return c = Array(c).fill().map(function(e){
return Array.isArray(p) ? p.clone() : p;
});
});
}
var arr = arrayND (2,3,4,"x");
console.log(JSON.stringify(arr));
关于javascript - 如何在 JavaScript 中实例化多维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43355935/