在数组中存储对象会覆盖值

时间:2017-01-05 02:13:31

标签: arrays node.js

我想存储一个对象数组,但是在对象存储在数组中之后,对它的任何引用都会改变原始值。

"use strict"

var array = []
var object = {}

object.animal = "Cow"
array.push(object)
object.animal = "Chicken"
array.push(object)

console.log(array) //[ { animal: 'Chicken' }, { animal: 'Chicken' } ]

修改 我现在明白对象存储为数组中的引用。避免这种情况的一种方法是按照下面的建议为每个项目声明一个对象,但是如何在循环中实现这一点,如下所示:

"use strict"

var array = []
var object = {}
var people = ["Mike Brown", "John Brown", "Mary Sue"]
var fname, sname

people.forEach(function(person) {
  [fname, sname] = person.split(" ")
  object.name = person
  object.fname = fname
  object.sname = sname
  array.push(object)
})

4 个答案:

答案 0 :(得分:3)

当您将object“推送”到数组时,它只会将引用推送到对象,而不是它的副本。

因此,在上面的代码中,只存在1个object。在您的“鸡”行中,您只需覆盖字符串“cow”。

我建议:

var array = []
array.push({animal: "cow"})
array.push({animal: "chicken"})

答案 1 :(得分:1)

这是100%正确的 这与内存在内部的工作方式有关。 它的工作原理是引用,而不是像PHP那样的值,例如PHP。

所以,如果你想在数组中有2个对象,其中一个包含字符串'cow',另一个包含'chicken',你可以做2个中的1个:

var array = []
var cow = {animal: 'Cow'};
var chicken = {animal: 'Chicken'};
array.push(cow);
array.push(chicken);
// Reason I'm including this option is because now you can now also do this
cow.farm = 'Kentucky farm';
chicken.eggsPerDay = 1.5;

或更快的方式,但不一定更好

var array = [];
array.push({animal: 'cow'});
array.push({animal: 'chicken'});

答案 2 :(得分:1)

您正在将对象的引用推送到数组上。你最终得到的是对同一个对象的两个引用。当您更改对象的属性时,您将影响对该对象的所有引用。

如果您需要复制一个可以使用的对象:

var timestr = current_timestamp().toDate()

答案 3 :(得分:0)

我遇到了同样的问题,但是我可以使用以下伪代码解决问题:

var array = [];

function addToArray(){
    var object = {}; //instantiate individual instance here. this is how to make a different value in array for each instance.

    object.animal = 'cow';
    array.push(object);


}
相关问题