Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用JavaScript在特定索引处的二维数组中填充数组_Javascript_Arrays - Fatal编程技术网

使用JavaScript在特定索引处的二维数组中填充数组

使用JavaScript在特定索引处的二维数组中填充数组,javascript,arrays,Javascript,Arrays,我想用特定索引处的项填充二维数组的内部数组。本例中的问题是,每个内部数组都填充了该项 尝试: 结果: 守则: 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) {

我想用特定索引处的项填充二维数组的内部数组。本例中的问题是,每个内部数组都填充了该项

尝试:

结果:

守则:

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)
   }
}

问题是,每年的数组都被99号填充,而且不仅像我所期望的那样,索引为99的数组。我做错了什么?

如Redu在评论中所述


内部数组都是彼此的引用

你可以像这样摆脱这个问题。它以某种方式克隆了数组,因此引用是不同的

Array.prototype.repeat= function(what, L){
  while(L) this[--L]= what.slice(0); // <--- Here
  return this;
};
Array.prototype.repeat=函数(what,L){

当(L)this[--L]=what.slice(0);//将相同的数组传递给
repeat
函数时,它将是对单个数组的365个引用

正确的方法是:

Array.prototype.repeat= function(L){
      while(L) this[--L]= new Array();
      return this;
};

为了生成正确的二维数组,所有嵌套数组项都应该是唯一的。由于对象在JS中是引用类型,因此在JS中生成多维数组时必须小心。创建多维数组的一种可能的通用方法是

Array.prototype.clone=function(){
返回此.reduce((p,c,i)=>(p[i]=Array.isArray(c)?c.clone():c,p),[]))
}
函数arrayND(…n){
返回n.reduceRight((p,c)=>c=(新数组(c)).fill(true).map(e=>Array.isArray(p)→p.clone():p));
}
yearsdays=arrayND(365,1,0);
yearsdays[6][0]=“星期日”;

console.log(yearsdays);
您的内部数组都是彼此的引用。请不要扩展内置原型。@gcampbell为什么不呢?@jackjop我应该纠正这一点,说“请不要扩展内置原型,除非从中心点开始,不要作为库的一部分供其他人使用。”@jackjop如果浏览器的下一个版本有自己的同名方法怎么办?您的扩展将覆盖它,这可能会破坏一切。
Array.prototype.repeat= function(L){
      while(L) this[--L]= new Array();
      return this;
};