for…in iterates over property names, not values, and does so in an unspecified order (yes, even after ES6). You shouldn’t use it to iterate over arrays. For them, there’s ES5’s forEach method that passes both the value and the index to the function you give it:
for in iterates over property names and does so in an unspecified order. You should not use it to iterate over arrays. For them, there is ES5’s forEach method that passes both the value and the index to the function you give it.
var myArray = [12, 15, 18, 32];
myArray.forEach(function (value, i) {
console.log('%d: %s', i, value);
});
Outputs:
0: 12
1: 15
2: 18
3: 32
Or you can use ES6’s Array.prototype.entries, which now has support across current browser versions:
for (const [i, value] of myArray.entries()) {
console.log('%d: %s', i, value);
}