我对 Javascript 很陌生,我似乎无法找到我的代码发生的情况的解释。
我想创建一个“人”数组,其中每个人都有一些与其关联的信息,例如“id”和“name”。我不知道我的数组中需要多少“人”,所以当我需要另一个人时我使用“推”。我的问题是我的数组最终填满了最后一个人的信息。
这是我正在使用的声明:
var ppl_arr = [];
var profile = {
id: 10000,
name: " ",
};
profile.id=3;
ppl_arr.push(profile); //add this person to my array
alert(ppl_arr[0].id + "\t" + ppl_arr.length);
profile.id=5;
ppl_arr.push(profile); // push next person to the array
alert(ppl_arr[0].id+"\t"+ppl_arr[1].id + "\t"+ppl_arr.length);
第一个警报正确显示:“3 1”
在第二个警报中,我得到“5 5 2”而不是“3 5 2”
因此,我在数组中添加了两个条目,但第二个条目似乎覆盖了第一个条目。谁能解释一下发生了什么?
最佳答案
您只需更改同一对象的 id,并将同一对象添加到数组中两次。我建议您将“人员”对象创建为实例对象,如下所示
//This is a constructor function for a Person object
function Person(id,name)
{
this.Id = id;
this.Name = name;
}
然后
var ppl_arr = [];
ppl_arr.push(new Person(3,"Bob")); //add this person to my array
alert(ppl_arr[0].Id + " - " + ppl_arr.length); //outputs "3 - 1"
//NOTE put a string inbetween, because Id and length are both integers,
//you would actual get a sum of the two, not a string concatenation.
ppl_arr.push(new Person(5,"Steve")); // push next person to the array
alert(ppl_arr[0].Id+"\t"+ppl_arr[1].Id + "\t"+ppl_arr.length); // outputs 3 5 2
关于javascript - Javascript 中的对象数组 - 使用 "push",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23417113/