被添加到阵列中时,新对象会被覆盖 [英] New objects get overwritten when being added to an array

查看:124
本文介绍了被添加到阵列中时,新对象会被覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新手在这里......是很好的。

Newbie here...be nice.

我将被推到一个数组的空对象。

I have an empty object that will get pushed into an array.

listView = {};

我添加属性给它。

I add properties to it.

listView.code = code;
listView.description = description;

我把成绩目标到一个数组中。

I push the results object into an array.

listy.push(listView);

每一次我在第2步进入一个新的选择,它会覆盖而不是增加新的对象属性到阵列的对象。它也由一个递增索引,因此它只是重复...

Each time I enter a new selection in step #2 it overwrites the object instead of adding the new object properties to the array. It also increments the index by one, so it just repeats...

[{"code":"I77.812","description":"Thoracoabdominal Aortic Ectasia"}]
[{"code":"I77.811","description":"Abdominal Aortic Ectasia"},{"code":"I77.811","description":"Abdominal Aortic Ectasia"}]
[{"code":"I06.1","description":"Rheumatic aortic insufficiency"},{"code":"I06.1","description":"Rheumatic aortic insufficiency"},{"code":"I06.1","description":"Rheumatic aortic insufficiency"}]

该数组应包含三个不同的对象。而是它有新加入的三个副本...

The array should contain three different objects. But instead it has three copies of the newly added one...

我应该如何添加新的选择对象,使他们不被覆盖?

How should I be adding the new choice objects so that they don't get overwritten?

推荐答案

您一直在增加同一个对象的引用,并改变了同一个对象,而不是增加新的对象。看到这一点:

You are always adding a reference to the same object, and changing that same object, instead of adding new objects. See this:

var a = [];
var o = {};
for (var i = 0; i < 5; i++) {
  o.id = i;
  a.push(o);
}
a
// => [{"id":4},{"id":4},{"id":4},{"id":4},{"id":4}]

var a = [];
for (var i = 0; i < 5; i++) {
  var o = {};
  o.id = i;
  a.push(o);
}
a
// => [{"id":0},{"id":1},{"id":2},{"id":3},{"id":4}]

的差,所述第二code总是使一个新的对象,它是从阵列中的已所有其他对象不同的

The difference is, the second code always makes a new object that is distinct from all other objects already in the array.

作为一个比喻,想象一个铸造戏剧导演。他变成一个演员,说:你......你会罗密欧。然后,他着眼于的相同的演员,说:你......你会茂丘西奥。在这里,茂丘西奥,拿这把剑。罗密欧......谁告诉你拿到一把剑?!?完全没有意识到,如果罗密欧与茂丘西奥是的同一人的,如果其中一人拿起一把剑,其他的这一点。

As a metaphor, imagine a theatre director in casting. He turns to an actor, says "You... you'll be Romeo.". Then he looks at the same actor, says "You... you'll be Mercutio. Here, Mercutio, take this sword. Romeo... who told you to get a sword?!?" completely failing to realise that, if Romeo and Mercutio are the same person, if one of them picks up a sword, the other does it too.

这篇关于被添加到阵列中时,新对象会被覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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