Javascript中的对象数组-使用;推;

Javascript中的对象数组-使用;推;,javascript,arrays,object,Javascript,Arrays,Object,我对Javascript非常陌生,我似乎找不到解释我的代码发生了什么 我想创建一个“人”数组,其中每个人都有一些与他们相关的信息,比如“id”和“name”。我不知道在我的数组中需要多少“人”,所以当我需要另一个人时,我会使用“推”。我的问题是我的数组最终充满了最后一个人的信息 以下是我使用的声明: var ppl_arr = []; var profile = { id: 10000, name: " ", }; profile.id=3; ppl_arr.push(profil

我对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”

所以我在数组中得到了两个条目,但第二个条目似乎覆盖了第一个条目。有人能解释发生了什么吗?

问题1:

警报(ppl\u arr[0].id+ppl\u arr.length)
将显示总和,而不是连接-尝试发出警报(ppl_arr[0].id.toString().concat(ppl_arr.length))

问题#2:

您可以更改现有对象的
id
属性,而不是复制它。因此,您也可以更改数组中已存在的对象的id。所以你需要

var ppl_arr = [];
var profile = {
  id: 10000,
  name: " ",

};

profile.id=3;
ppl_arr.push(profile);


//Create a new profile
var profile2 = { 
  id: 10000,
  name: " ",

};

profile2.id=5;
ppl_arr.push(profile2);
问题#1:

警报(ppl\u arr[0].id+ppl\u arr.length)
将显示总和,而不是连接-尝试发出警报(ppl_arr[0].id.toString().concat(ppl_arr.length))

问题#2:

您可以更改现有对象的
id
属性,而不是复制它。因此,您也可以更改数组中已存在的对象的id。所以你需要

var ppl_arr = [];
var profile = {
  id: 10000,
  name: " ",

};

profile.id=3;
ppl_arr.push(profile);


//Create a new profile
var profile2 = { 
  id: 10000,
  name: " ",

};

profile2.id=5;
ppl_arr.push(profile2);

您只需更改同一对象的id,并将同一对象添加到数组中两次。我建议您将“人员”对象创建为实例对象,类似这样

//This is a constructor function for a Person object

function Person(id,name)
{
    this.Id = id;
    this.Name = name;
}
然后


您只需更改同一对象的id,并将同一对象添加到数组中两次。我建议您将“人员”对象创建为实例对象,类似这样

//This is a constructor function for a Person object

function Person(id,name)
{
    this.Id = id;
    this.Name = name;
}
然后


将新值指定给对象的特性不会使其成为新对象。您只需将完全相同的对象放入数组两次。此外,您的第一个
alert()
显示
4
,而不是
3
(“id”值),因为您将两个数字相加(
3
和数组的长度,即
1
,给出
4
)。为对象的属性指定新值不会使其成为新对象。您只需将完全相同的对象放入数组中两次。此外,您的第一个
alert()
显示
4
,而不是
3
(“id”值),因为您将两个数字相加(
3
和数组长度,即
1
,给出
4
),谢谢!我越来越近了!这个例子帮助我了解了对象数组的情况。谢谢!我越来越近了!这个例子帮助我了解了对象数组的情况。