我想用特定索引处的项目填充二维数组的内部数组。本例中的问题是每个内部数组都填充了该项目。
代码:
Array.prototype.repeat= function(what, L){
while(L) this[--L]= what;
return this;
};
var yearsdays = [].repeat([], 365);
for(var i = 0; i<= yearsdays.length; i++){
if(i === 99) {
yearsdays[i].push(99)
}
}
结果:
Array[365]
[0 … 99]
0: Array[1]
0: 99
length: 1
__proto__: Array[0]
1: Array[1]
0: 99
length: 1
__proto__: Array[0]
2: Array[1]
0: 99
length: 1
__proto__: Array[0]
and etc.......
问题是,结果yeardays中的每个数组都填充了数字99,但不仅仅是我期望的索引为99的数组。我做错了什么?
最佳答案
正如 Redu 在评论中所说
Your inner arrays are all references of each other
你可以这样摆脱这个问题。它以某种方式克隆了数组,因此引用是不同的。
Array.prototype.repeat= function(what, L){
while(L) this[--L]= what.slice(0); // <--- Here
return this;
};
关于javascript - 使用 JavaScript 将数组填充到特定索引处的二维数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37628778/