Javascript:使用非连续键迭代数组 [英] Javascript: Iterating over array with non-consecutive keys

查看:168
本文介绍了Javascript:使用非连续键迭代数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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";

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

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
}

什么是处理这个问题的规范方法,看作 for-each语法并非意图用于在javascript 中迭代数组中的值?谢谢。

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.

推荐答案

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

The idiomatic way would be to use an object, not an array. Just be sure to check hasOwnProperty to make sure you don't pick up stray things which 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]);
});

如果您计划在IE等旧版浏览器中运行该代码,请务必使用Babel进行转换。

Be sure to transpile that code with Babel if you plan on running it in older browsers like IE.

这篇关于Javascript:使用非连续键迭代数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆