Date: 2010jul19
Updated: 2017jun8
Language: javaScript
Level: beginner
Keywords: loop
Q. How to I enumerate everything in a javaScript array?
A. If it is NOT an associative array use a for-loop like this:
const a = [ 'apple', 'ibm', 'microsoft' ];
I prefer this way:
for (let i in a) {
let element = a[i];
// Do something with element
}
This works because a is actually:
const a = { 0: 'apple', 1: 'ibm', 2: 'microsoft' };
The conventional way:
for (let i = 0; i < a.length; i++) {
let element = a[i];
// Do something with element
}
ECMASscript 2015 introduced "of" which is nice, but can't be relied on:
for (let element of a) {
// Do something with element
}