Javascript: Iterating over an array using non-sequential keys

I need to iterate over an array for which the keys are not sequential:

var messages = new Array();
messages[0] = "This is the first message";
messages[3] = "This is another message";

Obviously, using a for loop index will not work, since it depends on sequential keys:

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 to handle this, since for each syntax it is not intended to iterate over values ​​in an array in javascript ? Thank.

+5
source share
7 answers

An idiomatic way would be to use an object, not an array. Just remember to check hasOwnPropertyto make sure that you are not picking up stray items that 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]); 
}

, Object.keys

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

Babel, , IE.

+9
for(var i in messages)
{
    console.log(messages[i]);
}
+3

undefined...

for (var i=0 ; i<messages.length ; i++) {
    if(messages[i] !== undefined)
        alert(messages[i]);
}

forEach, undefined...

messages.forEach(function(v,i) {
    alert(v);
});
+3

Simple! , :

for (var i = 0 ; i < messages.length; i += gap) {
    alert(messages[i]); // Will only alert the messages at the regular interval/gap 
}
+2

each() jQuery.

$.each(messages, function(index, val){
    alert(val); 
});

jQuery docs

each()

, . length (, ) , 0 -1. .

+1
source

When you create an array and give it values ​​in the 0and values 3, undefinedare created in 1and 2. try the following:

$.each(messages, function(i,val) { 
  if (val) {
    alert(val);
  } 
});
+1
source

For the case of using this with assumptions:

array.length >== 1 (i.e. an array with significant data in it already)

If you are interested in data from array[1], array[15], array[45]etc.

You can do something similar to:

var array = ["you","will","become","strong","with","the","codes","padawan"];
var values = [1,5,7];


for (var i = 0; i < values.length; i++){
    var cypher = values[i];
    console.log(array[cypher]);
}
//will, the, padawan

Or perhaps something more meaningful, for example:

for (var i = 0; i < values.length; i++){
    var cypher = values[i];
    aService.aFn.(array[cypher],cb);
}
//calls aService.aFn separately for each value array[1] , array[5] , array[7] passed as args
0
source

All Articles