Reputation: 63
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);
}
Upvotes: 1
Views: 84
Reputation: 595
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.
Upvotes: 0
Reputation: 163
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);
}
Upvotes: -1
Reputation: 43
You are using the "this" keyword incorrectly. When you access family[i] you are already accessing an instance of that prototype in JavaScript. Just drop the "this."
Upvotes: 3