Taylor Liss Taylor Liss - 4 years ago 75
Javascript Question

Object method doesn't get run in for loop

In this code, I create an array of objects and attempt to loop through them calling a method on each one. The method is part of the objects' prototype.

Here's the setup:

function TestObj(name) {
this.name = name;
}

TestObj.prototype.speak = function() {
console.log(this.name);
};

var myArray = [
new TestObj('first'),
new TestObj('second')
];


I know I can access the method correctly because this gives the proper output:

myArray[0].speak(); // displays "first"


However, both of the loops I tried won't output anything:

for (var i = 0; i < myArray.length; i++) {
myArray[i].speak();
}

for (var key in myArray) {
key.speak();
}

Answer Source

I your second loop key.speak(); to myArray[key].speak();

for (var key in myArray) {
   myArray[key].speak();
}

function TestObj(name) {
    this.name = name;
}

TestObj.prototype.speak = function() {
    console.log(this.name);
};

var myArray = [
    new TestObj('first'),
    new TestObj('second')
];
for (var i = 0; i < myArray.length; i++) {
    myArray[i].speak();
}

for (var key in myArray) {
    myArray[key].speak(); /*change here in your code*/
}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download