我只想打印数组中的第一个值(名称)



在下面的代码中,我试图打印出数组的第一个值(名称(,但它没有像我预期的那样工作:

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); 
}

您错误地使用了"this"关键字。当你访问 family[i] 时,你已经在 JavaScript 中访问了该原型的实例。只需删除"这个"。

要从数组中获取第一项,您可以在没有循环的情况下执行以下操作:

console.log(family[0].name);

没有循环,因为如果您知道要打印哪个项目,则不需要循环。

或者,如果需要循环,您可以添加一些逻辑,例如

if(i === 0) {
console.log(family[0].name);
}

访问数组中对象的name属性时不需要使用this

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); 
}

相关内容