Loop The Loop


#1

https://www.codecademy.com/en/courses/spencer-sandbox/4/2

The program works like it’s supposed to, but I get the error “Oops, try again. It looks like the object at index 0 was not created with the Person constructor” AND “TypeError: Cannot read property ‘name’ of undefined”

// Our Person constructor
function Person(name,age) {
  this.name = name;
  this.age = age;
}

// Now we can make an array of people
var family = [alice, bob, michelle, timmy];

var alice = new Person("Alice", 40);

var bob = new Person("Bob", 42);

var michelle = new Person("Michelle", 8);

var timmy = new Person("Timmy", 6);

// loop through our new array

for (i = 0; i <= family.length; i++){
    console.log(family[i].name);
}

#2

In order for this to work, the objects need to be already defined. Write the above line just before the loop, and after the objects are defined.

If you have covered the Array.push() method, you could use it and just start with an empty array where your list is currently.

var family = [];

Then instead of creating standalone objects (which is what they are, currently) push the new object straight to the array.

family.push(new Person(...));

This way there is only one global variable, not five, and the array is extendable in the exact same way for new additions. The objects will exist in the array, only.


#3
//Person Constructor
function Person(name,age) {
  this.name = name;
  this.age = age;
}


//Array
var family = [];
//people
var alice = new Person("alice", 40);

var bob = new Person("bob", 42);

var michelle = new Person("michelle", 8);

var timmy = new Person("timmy", 6);
//Array Push
family.push(alice, bob, michelle, timmy)
// Loop

for (i = 0; i <= family.length; i++){
    console.log(family[i].name);
}

=====================
“TypeError: Cannot read property ‘name’ of undefined” :confused:


#4
alice
bob
michelle
timmy
TypeError: family[i] is undefined

i must always be less than family.length.

You still have not addressed the problem of populating the global namespace with vulnerable objects. And you are wasting memory. Create the objects driectly in the array, not globally.


#5

Ah-ha! It worked! Thank you so much!


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.