I need to iterate over an array for which the keys are non-consecutive:
var messages = new Array();
messages[0] = "This is the first message";
messages[3] = "This is another message";
Obviously using the index of a for loop will not work as it depends on the keys being sequential:
for (var i=0 ; i<messages.length ; i++) {
alert(messages[i]); // Will only alert the first message, as i is never equal to 3
}
What is the canonical way of dealing with this, seeing as the for-each syntax is not intended for iterating over values in an array in javascript? Thanks.
For a use case such with the assumptions:
array.length >== 1
(i.e: an array with meaningful data in it already)Where you are interested in the data from
array[1], array[15], array[45]
etcYou can do something similar to:
Or perhaps something more meaningful such as:
You can use
each()
jQuery method to do this.From jQuery docs
each()
When you create an array and give it values at
0
and3
,undefined
values are created at1
and2
. try this:The idiomatic way would be to use an object, not an array. Just be sure to check
hasOwnProperty
to make sure you don't pick up stray things which may have been added to the prototype.Or, the more modern way would be to use
Object.keys
Be sure to transpile that code with Babel if you plan on running it in older browsers like IE.
Simple! if the array has regular gaps between the indices do this: