gpt4 book ai didi

javascript - 如何更好地迭代包含大量未定义项的大型数组

转载 作者:行者123 更新时间:2023-11-28 16:38:07 25 4
gpt4 key购买 nike

考虑以下代码:

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 个值。有什么办法可以更快吗?即使使用另一个按数字索引对象然后快速循环它们的系统?

最佳答案

您可以使用 for/in 循环:

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

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

这正是您正在寻找的;它只会循环实际定义的索引,并跳过数组中的任何空洞。

关于javascript - 如何更好地迭代包含大量未定义项的大型数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2709704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com