我需要遍历一个键不连续的数组:
var messages = new Array();
messages[0] = "This is the first message";
messages[3] = "This is another message";
显然,使用 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
}
处理这个问题的规范方法是什么,见 the for-each syntax is not intended for iterating over values in an array in javascript ?谢谢。
最佳答案
惯用的方法是使用对象,而不是数组。请务必检查 hasOwnProperty
以确保您不会拾取可能已添加到原型(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]);
});
如果您计划在 IE 等较旧的浏览器中运行该代码,请务必使用 Babel 对其进行转换。
关于Javascript:使用非连续键迭代数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9066503/