DrCensor
DrCensor

Reputation: 63

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

Upvotes: 1

Views: 84

Answers (3)

Cookie
Cookie

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

dogpunk
dogpunk

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

Eric Swenson
Eric Swenson

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

Related Questions