var myArray = new Array();
var increment = 0;
myArray.push('Tom Hanks', 'Pierce Brosnan', 'Will Smith', 'Richard Ayoade');
for (actor in myArray) {
console.log(actor + ' is my #' + increment + ' choice.');
increment++;
}
Something is wrong with this for loop, and I believe its 'actor' in the for-in loop. This prints out a number where the name of the actor should be.
Coming from Ruby, this looks like a .each method iterating over each element in the array, but obviously this is going about things a bit differently. Can anyone explain why this isn't working?
Just picked up JS today. Thanks.
Thats not how for ... in
works. From that link:
A
for...in
loop iterates over the properties of an object in an arbitrary order
And:
for..in
should not be used to iterate over an Array where index order is important. Array indexes are just enumerable properties with integer names and are otherwise identical to general Object properties. There is no guarantee that for...in will return the indexes in any particular order and it will return all enumerable properties, including those with non–integer names and those that are inherited.
Given that you are passing in an array the properties are the indexes for the items it holds.
This is why you are getting the index and not the name.
If you want to retain order and print the names, you need a "traditional" for loop, like so:
for (var i = 0; i < myArray.length; i++) {
console.log(myArray[i] + ' is my #' + (i+1) + ' choice.');
}
The reason to be careful when using for .. in
is it can have unexpected results. Checkout this jsFiddle...
var myArray = new Array();
var increment = 0;
myArray.push('Tom Hanks', 'Pierce Brosnan');
myArray.hello = "what?";
for (actor in myArray) {
alert(actor + ' is my #' + increment + ' choice.');
increment++;
}
for (var i = 0; i < myArray.length; i++) {
alert(myArray[i] + ' is my #' + (i+1) + ' choice.');
}
In this example, the first loop will iterate 3 times, picking up the 'hello' property as well as the rest in the array. While the second only does the 2 formal items in the array.