Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Iterating over array with non-consecutive keys

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.

like image 224
dotancohen Avatar asked Jan 30 '12 15:01

dotancohen


2 Answers

for(var i in messages)
{
    console.log(messages[i]);
}
like image 126
locrizak Avatar answered Oct 16 '22 16:10

locrizak


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.

var messages = { };
messages[0] = "This is the first message";
messages[3] = "This is another message";

for (var i in messages) {
    if (messages.hasOwnProperty(i))
        alert(messages[i]); 
}

Or, the more modern way would be to use Object.keys

Object.keys(messages).forEach(prop => {
    alert(messages[prop]);
});

Be sure to transpile that code with Babel if you plan on running it in older browsers like IE.

like image 26
Adam Rackis Avatar answered Oct 16 '22 17:10

Adam Rackis