Javascript:使用非连续键迭代数组
我需要迭代一个键不连续的数组:
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 中迭代数组中的值?谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
惯用的方法是使用对象,而不是数组。请务必检查
hasOwnProperty
以确保您不会拾取可能已添加到原型中的杂散内容。或者,更现代的方法是使用
Object.keys
如果您计划在 IE 等旧版浏览器中运行该代码,请务必使用 Babel 转译该代码。
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.Or, the more modern way would be to use
Object.keys
Be sure to transpile that code with Babel if you plan on running it in older browsers like IE.
您可以忽略
undefined
属性...或者使用
forEach
,它将忽略未声明的属性...undefined
You could ignore the
undefined
properties...Or use
forEach
, which will ignoreundeclared properties...undefined
简单的!如果数组的索引之间有规则的间隙,请执行以下操作:
Simple! if the array has regular gaps between the indices do this:
您可以使用
each()
jQuery 方法来执行此操作。来自 jQuery 文档
each()
You can use
each()
jQuery method to do this.From jQuery docs
each()
当您创建数组并在
0
和3
处为其指定值时,会在1
和1
处创建undefined
值。代码>2。试试这个:When you create an array and give it values at
0
and3
,undefined
values are created at1
and2
. try this:对于假设如下的用例:
array.length >== 1
(即:其中已经包含有意义数据的数组)
如果您对 array[1]、array[15]、array[45] 等中的数据感兴趣,
您可以执行类似以下操作:
或者也许是更有意义的事情,例如:
For a use case such with the assumptions:
array.length >== 1
(i.e: an array with meaningful data in it already)
Where you are interested in the data from
array[1], array[15], array[45]
etcYou can do something similar to:
Or perhaps something more meaningful such as: