The simple answer is this: for in
loops iterate over properties of an object. An array
in JavaScript is an object that's indexed. So, your example is actually this:
Array[4]
0: "Tom Hanks"
1: "Pierce Brosnan"
2: "Will Smith"
3: "Richard Ayoade"
length: 4
__proto__: Array[0]
When you use your for/in
code,
for (actor in myArray) {
console.log(actor + ' is my #' + increment + ' choice.');
increment++;
}
actor
is the property at the time of iteration (0, 1, 2, 3...)
To access the value in your for in
loop would require your code to be updated like this:
for (idx in myArray) {
console.log(myArray[idx] + ' is my #' + idx + ' choice.');
}
However, it's considered bad practice to use for in
loops to iterate an array. For example, what if I did something like this:
myArray.type = "Actors";
The console log would return something like:
// 'Actors is my type choice'
Probably not the intended output. Instead, for array iteration, take a look at the for
loop or forEach
method of arrays.
for (var increment = 0, len = myArray.length; increment < len; increment += 1) {
console.log(myArray[increment] + ' is my #' + increment + ' choice.');
}
// or...
myArray.forEach(function(actor, increment) {
console.log(actor + ' is my #' + increment + ' choice.');
});