Let\'s say I have
myArray = [\'item1\', \'item2\']
I tried
for (var item in myArray) {console.log(item)}
It
In ES5 there is no efficient way to iterate over a sparse array without using the length property. In ES6 you can use for...of. Take this examples:
'use strict';
var arr = ['one', 'two', undefined, 3, 4],
output;
arr[6] = 'five';
output = '';
arr.forEach(function (val) {
output += val + ' ';
});
console.log(output);
output = '';
for (var i = 0; i < arr.length; i++) {
output += arr[i] + ' ';
}
console.log(output);
output = '';
for (var val of arr) {
output += val + ' ';
};
console.log(output);
All array methods which you can use to iterate safely over dense arrays use the length
property of an object created by calling ToObject
internaly. See for instance the algorithm used in the forEach
method: http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18
However in es6, you can use for...of safely for iterating over sparse arrays.
See also Are Javascript arrays sparse?.