我需要迭代一个键不连续的数组:
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
}
处理这个问题的规范方法是什么?for-each 语法不适用于在 javascript 中迭代数组中的值 https://stackoverflow.com/questions/9065358/javascript-object-property-not-in-scope?谢谢。
惯用的方法是使用对象,而不是数组。请务必检查一下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]);
}
或者,更现代的方法是使用Object.keys
Object.keys(messages).forEach(prop => {
alert(messages[prop]);
});
如果您计划在 IE 等旧版浏览器中运行该代码,请务必使用 Babel 转译该代码。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)