更改JS数组中的单个对象会更改所有元素 [英] Changing single object in JS array changes all elements

查看:400
本文介绍了更改JS数组中的单个对象会更改所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有71个对象的数组:

  var data = [] 

我用来自数据库的数据填充该数据,该数据库包含填充 data

  angular.forEach(returnData,function(value,index){
if(!Array .isArray(value)){
tempObject [key] = value;
}
});
for(i = 0; i< 71; i ++){
data.push(tempObject);
}

因此,从角度来看,我从返回数据中获取了所有静态元素,为其创建一个对象,然后将该对象重复71次。因此数据可能开始像这样:

  [
{'a':1,
'b':2,
'd':7
},
{'a':1,
'b':2,
'd': 7
}
]

然后我去抓取所有作为数组传递回来,并尝试将它们添加到 data 数组中。



但是,一旦我添加第一个元素,它为数组中的每个对象设置相同的元素。



这意味着 data [0] ['c'] = 11 ; 将导致:

  [
{'a':1,
'b':2,
'c':11,
'd':7
},
{'a':1,
'b ':2,
'c':11,
'd':7
}
]

即使我没有触及数组中的第二个索引。当我更新第二个索引时,它也会同时更新第一个索引。我确定这里是我所缺少的。



谢谢!

解决方案

您只是将对 tempObject 的引用推入 data 数组中的71个不同位置。因此, data [0] data [1] 等都指向同一个对象,这就是为什么



如果要实际推送71个单独的实例,则必须克隆 tempObject

最后,我检查过,克隆一个普通的旧JavaScript对象的最有效方法是字符串化,然后重新解析:

  data.push(JSON.parse(JSON.stringify(tempObject))); 


I have an array of 71 objects:

var data = []

I populate this with data coming from a database that contains both static and dynamic elements of the objects that populate data.

angular.forEach(returnData,function(value,index) {
  if(!Array.isArray(value)) {
    tempObject[key] = value;
  }
});
for(i = 0; i < 71; i++) {
  data.push(tempObject);
}

So, in angular, I grab every element that is static from the return data, create an object of it, and repeat that same object 71 times. So the data might start out something like this:

[
  {'a': 1,
   'b': 2,
   'd': 7
  },
  {'a': 1,
   'b': 2,
   'd': 7
  }
]

I then go and grab all of the elements that are passed back as arrays and try and add them to the data array.

However, as soon as I add the first element, it sets that same element for every object in the array.

Meaning that data[0]['c'] = 11; will result in:

[
  {'a': 1,
   'b': 2,
   'c': 11,
   'd': 7
  },
  {'a': 1,
   'b': 2,
   'c': 11,
   'd': 7
  }
]

even though I haven't touched the second index in the array. And when I update the second index it will update the first index as well. I'm sure there is something that I'm missing here.

Thanks!

解决方案

You're just pushing a reference to tempObject into 71 different positions in your data array. Therefore data[0], data[1], and so on are all pointing to the same object which is why you see changes reflected across the array.

If you want to actually push 71 separate instances, you have to clone tempObject every time you push it on to the array.

Last I checked, the most efficient way to clone a plain old JavaScript object was to string-ify and then re-parse:

data.push(JSON.parse(JSON.stringify(tempObject)));

这篇关于更改JS数组中的单个对象会更改所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆