【发布时间】:2012-02-22 09:39:33
【问题描述】:
我需要遍历一个键不连续的数组:
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?谢谢。
【问题讨论】:
-
你最初是如何得到这样一个数组的?与其寻找一些技巧来迭代它,为什么不从根本上解决问题 => 这就是你获得这个数组的方式。
-
您是否考虑过使用对象来代替?
{ "0": "this is the first message", "3": "this is another message"} -
只会提醒第一条消息,因为 i 永远不会等于 3 这是不正确的。
messages.length将是4。 -
数组代表对象,而不是示例中的简单字符串文字。数组键是数据库主键。将主键作为对象的另一个属性会导致各种复杂性,因为我通常知道通过 ID 访问哪个对象,因此将 ID 作为数组键非常方便。也就是说,除了这一问题。
-
@Yoshi:你是对的,循环必须抛出异常并在遇到无效数组键时退出。无论哪种方式,这种方法都行不通!
标签: javascript jquery oop iterator