遍历JS数组的已定义元素 [英] Iterate over defined elements of a JS array

查看:38
本文介绍了遍历JS数组的已定义元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JS数组将ID映射到实际元素,即键值存储.我想遍历所有元素.我尝试了几种方法,但都有一些注意事项:

I'm using a JS array to Map IDs to actual elements, i.e. a key-value store. I would like to iterate over all elements. I tried several methods, but all have its caveats:

for (var item in map) {...}

对数组的所有属性进行迭代,因此它还将包括Array.prototype的函数和扩展.例如,将来有人在Prototype库中放手,就会制止现有的代码.

Does iterates over all properties of the array, therefore it will include also functions and extensions to Array.prototype. For example someone dropping in the Prototype library in the future will brake existing code.

var length = map.lenth;
for (var i = 0; i < length; i++) {
  var item = map[i];
  ...
}

可以工作,但是就像

$.each(map, function(index, item) {...});

它们遍历索引0..max(id)的整个范围,这具有可怕的缺点:

They iterate over the whole range of indexes 0..max(id) which has horrible drawbacks:

var x = [];
x[1]=1;
x[10]=10;
$.each(x, function(i,v) {console.log(i+": "+v);});

0: undefined
1: 1
2: undefined
3: undefined
4: undefined
5: undefined
6: undefined
7: undefined
8: undefined
9: undefined
10: 10

当然,我的ID也不会像连续序列.此外,它们之间可能会有巨大的差距,因此出于性能原因,在后一种情况下跳过未定义是不可接受的.如何安全地仅迭代数组的已定义元素(以在所有浏览器和IE中都有效的方式)?

Of course my IDs wont resemble a continuous sequence either. Moreover there can be huge gaps between them so skipping undefined in the latter case is unacceptable for performance reasons. How is it possible to safely iterate over only the defined elements of an array (in a way that works in all browsers and IE)?

推荐答案

使用 for ... in 中的> hasOwnProperty 中,以确保不包括原型添加项:

Use hasOwnProperty within for ... in to make sure that prototype additions aren't included:

for (var item in map)
  if (map.hasOwnProperty(item)) {
    // do something
  }

这篇关于遍历JS数组的已定义元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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