我想要一个包含 Person 对象的 People 数组,以便我可以从数组索引访问该对象中的字段。
通常我会选择对象集合或列表等。
你能帮我完成这个工作吗?...
var people = [];
var person = {
firstName:"John",
age:50
};
function newPerson(){
var p = new person(); //<<< #1. Is this a good approach in JS?
p.firstName = "Fred";
p.age = 21;
people.push(p);
}
function totalAge(){
var totalAge =0;
for (i = 0; i < people.length; i++){
totalAge += people[i].age; //<<<<< #2. This is the kind of access I want.
}
}
最佳答案
试试这个,JsBin sourses
var people = [];
function Person(name, age){ // Function constructor
this.name = name; // do not forget 'this.'
this.age = age;
}
function addPerson(name,age){
var p = new Person(name,age); // here we create instance
people.push(p);
}
addPerson("Petia", 80);
addPerson("Vasia", 20);
function totalAge(){
var total = 0; // do not name local variables same as function
var i; // use var for i variable, otherwise it would be global variable
for (i = 0; i < people.length; i++){
total += people[i].age;
}
return total;
}
var total = totalAge();
console.log(total);
关于javascript - 使用构造函数创建对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24353095/