[英]i just want to print the first value(name) from the array
In the below code I am trying to print out just the first value (name) of the array, but it doesn't work as I expect: 在下面的代码中,我试图仅打印出数组的第一个值(名称),但是它无法正常工作:
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);
}
You are using the "this" keyword incorrectly. 您错误地使用了“ this”关键字。 When you access family[i] you are already accessing an instance of that prototype in JavaScript. 当您访问family [i]时,您已经在JavaScript中访问该原型的实例。 Just drop the "this." 只需删除“ this”。
To get the first item from the array you could do the below without the loop: 要从数组中获取第一项,可以执行以下操作而无需循环:
console.log(family[0].name);
Without looping, as the loop is unnecessary if you know which item you want to print. 没有循环,因为如果知道要打印的项目,则不需要循环。
Or, if the loop is necessary you could add some logic such as 或者,如果需要循环,则可以添加一些逻辑,例如
if(i === 0) {
console.log(family[0].name);
}
You do not need to use this
when accessing the name
property of the object in the array. 访问数组中对象的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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.