在下面的代码中,我试图打印出数组的第一个值(名称),但它没有像我期望的那样工作:
function Person (name, age) {
this.name = name;
this.age = age;
}// Our Person constructor
// Now we can make an array of people
var family = new Array();
family[0] = new Person("alice", 40);
family[1] = new Person("bob", 42);
family[2] = new Person("michelle", 8);
family[3] = new Person("timmy", 6);
// loop through our new array
for(i = 0; i <= family.Length; i++) {
console.log( family[i].this.name);
}
答案 0 :(得分:3)
您错误地使用了“this”关键字。当您访问family [i]时,您已经在JavaScript中访问该原型的实例。只需删除“这个。”
答案 1 :(得分:0)
要从数组中获取第一项,您可以在没有循环的情况下执行以下操作:
console.log(family[0].name);
没有循环,因为如果您知道要打印哪个项目,则不需要循环。
或者,如果需要循环,您可以添加一些逻辑,例如
if(i === 0) {
console.log(family[0].name);
}
访问数组中对象的this
属性时,无需使用name
。
答案 2 :(得分:-1)
function Person (name, age) {
this.name = name;
this.age = age;
}// Our Person constructor
// Now we can make an array of people
var family = new Array();
family[0] = new Person("alice", 40);
family[1] = new Person("bob", 42);
family[2] = new Person("michelle", 8);
family[3] = new Person("timmy", 6);
// loop through our new array
for(i = 0; i < family.length; i++) {
console.log( family[i].name);
}