2010-04-25 24 views
0

考虑下面的代码的一个巨大的数组:如何更好地遍历,有很多不确定的项目

var _test1 = []; 
_test1[88] = 'sex'; 
_test1[1999990] = 'hey'; 
for(i = 0, length = _test1.length; i < length; i++){ 
    if(_test1[i] == 'hey'){ 
     alert(_test1.length); 
    } 
} 

这需要大量的时间,而且只有2个值。 有什么办法可以加快速度吗?即使通过使用另一个通过数字索引对象然后循环它们的系统?

回答

1

您是否尝试过使用对象?数字应自动转换为字符串。你将遍历一个for ... in循环的列表。

+0

您不需要切换到对象。 – SLaks 2010-04-25 19:59:21

+0

是的。我认为这是最好的选择。比数组重要得多吗? – 2010-04-25 20:01:19

+0

数组是对象。 – SLaks 2010-04-25 20:05:00

3

您可以使用for/in循环:

for (var i in _test1) { 
    if (!_test1.hasOwnProperty(i) || isNaN(+i)) continue; 

    if(_test1[i] == 'hey'){ 
     alert(_test1.length); 
    } 
} 

这正是你要寻找的;它只会遍历实际定义的索引,并会跳过数组中的任何空洞。

+0

感谢这个解决方案,我稍后会进行基准测试:D – 2010-04-25 20:22:12