[removed] Iterating over array with non-consecutiv

2019-04-07 03:23发布

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.

7条回答
Fickle 薄情
2楼-- · 2019-04-07 04:23

You could ignore the undefined properties...

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

Or use forEach, which will ignore undefined undeclared properties...

messages.forEach(function(v,i) {
    alert(v);
});
查看更多
登录 后发表回答