Javascript:使用非连续键迭代数组

dot*_*hen 7 javascript oop jquery iterator

我需要迭代一个非连续键的数组:

var messages = new Array();
messages[0] = "This is the first message";
messages[3] = "This is another message";
Run Code Online (Sandbox Code Playgroud)

显然使用for循环的索引将不起作用,因为它取决于顺序的键:

for (var i=0 ; i<messages.length ; i++) {
    alert(messages[i]); // Will only alert the first message, as i is never equal to 3
}
Run Code Online (Sandbox Code Playgroud)

什么是处理这个的规范方法,因为for-each语法不是用于在javascript中迭代数组中的值?谢谢.

Ada*_*kis 10

惯用的方法是使用一个对象,而不是一个数组.请务必检查hasOwnProperty以确保您不会拾取可能已添加到原型中的杂散物.

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]); 
}
Run Code Online (Sandbox Code Playgroud)

或者,更现代的方式是使用 Object.keys

Object.keys(messages).forEach(prop => {
    alert(messages[prop]);
});
Run Code Online (Sandbox Code Playgroud)

如果您计划在IE等旧版浏览器中运行它,请务必使用Babel来传输该代码.


loc*_*zak 5

for(var i in messages)
{
    console.log(messages[i]);
}
Run Code Online (Sandbox Code Playgroud)