我正在尝试打印循环中每个人的姓名 但是我得到3次未定义。我该如何解决这个问题?
var Person = function(name,age){
self.name = name;
self.age = age;
};
family = {};
family[0] = new Person("mark", 3);
family[1] = new Person("tom", 12);
family[2] = new Person("michael", 45);
family[3] = new Person("joe", 65);
for (i=0; i<4; i++) {
member = family[i];
console.log(member.name);
}
答案 0 :(得分:2)
JavaScript中没有self
个关键字。你的意思是this
:
this.name = name;
this.age = age;
答案 1 :(得分:1)
您应该在this
对象中使用self
,而不是Person
。
作为备注,您可能希望var
,family
和i
前面有member
。 (除非你希望那些是全球性的)
另外,请注意您正在设置一个对象文字,它作为哈希而不是数组。不知道你的意图。
答案 2 :(得分:1)
您希望使用此而不是self,否则对象将无法正确构造。您还可以使用push将元素添加到数组而不是使用索引。
var Person = function(name,age){
this.name = name;
this.age = age;
};
family = [];
family.push(new Person("John", 40));
family.push(new Person("Paul", 69));
family.push(new Person("George", 58));
family.push(new Person("Ringo", 71));
for (var i=0; i < family.length; i++) {
console.log(family[i].name);
}