迭代的Javascript通过稀疏数组 [英] Javascript iterating through sparse array

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

问题描述

我有一个稀疏数组(索引不是连续的)是这样的:

I have a sparse array (indexes are not consecutive) like this:

var testArray = { 0: "value1", 5: "value2", 10: "value3", 15: "value4" };

我只是想通过各个项目进行迭代,做一些东西,并且能够在一定条件下打破。

I would simply like to iterate through each item, do some stuff, and be able to break under a certain condition.

我是相当新的Javascript和我没有找到一个合适的方式来做到这一点。这里是我的尝试:

I am fairly new to Javascript and I didn't find a proper way to do it. Here is what I tried:


  1. 内置的for..in。看来,这是不是通过数组迭代

<一个href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach\">forEach从ECMASCRIPT5。这一次迭代正确的,但我不能从回路断线。

forEach from ECMASCRIPT5. This one iterate correctly, but I cannot break from the loop.

_.each()从Underscore.js 。同样的结果#2。

$。每()从JQuery的。这一个我可以返回假突破,但它不会正确地迭代。对于上面的例子中,而不是在迭代0,5,10,15,它会遍历在0,1,2,3,4,5,6 ......这显然不是我所期望的。

$.each() from JQuery. With this one I can break by returning false, but it won't iterate correctly. For the above example, instead of iterating at 0, 5, 10, 15, it will iterate at 0,1,2,3,4,5,6... which is obviously not what I expect.

所以我的问题是:有没有一种简单的方法来迭代稀疏阵列的可能性JavaScript中的循环中,打破或将它更好地使用另一种数据结构像一个哈希表?如果是这样,任何recommandation?

谢谢!

推荐答案

什么是错的为中... 语法?你有一个对象,让为中... 语法是完全有效的使用方法:

What's wrong with the for...in syntax? You have an object so the for...in syntax is completely valid to use:

var testArray = { 0: "value1", 5: "value2", 10: "value3", 15: "value4" };

for (var key in testArray) {
  var value = testArray[key];

  if (...) {
    break;
  }
}

这篇关于迭代的Javascript通过稀疏数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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