在具有“孔"的阵列上迭代.在JavaScript中 [英] Iterating over an array with "holes" in JavaScript

查看:48
本文介绍了在具有“孔"的阵列上迭代.在JavaScript中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,将从中删除一些项目;但是仍然有一些循环在运行,所以我只想跳过删除对象的地方

I have got an array from which some items are going to be removed; but some loops are still running on them, so I want to simply skip the places where I remove my objects

我知道for(i in array)的语法应该这样做,因为它会在索引上进行迭代,但是那我该如何删除我的项目呢?因为当我执行array [4] = null时,我的for无关紧要,并继续尝试使用4处的值.

I know that the syntax for(i in array) should do this because it iterates on the index, but how should I remove my items then ? Because when i do array[4] = null, my for just doesn't care and goes on trying to use the value at 4.

我也试图检查是否为空,但没有成功... 谢谢

I also tried to check if !null but without success... thank you

推荐答案

如果要删除项目而不留下孔,则应使用.splice()

If you want to remove an item without leaving a hole, you should use .splice()

myarray.splice(idx, 1);


但是,如果您说要想要那里的孔,但想跳过它们,则可以使用delete删除项目(留下一个孔),并使用.forEach()进行迭代,从而跳过漏洞.


But if you're saying that you want the holes there, but want to skip them, then you can use delete to remove the item (leaving a hole), and use .forEach() for the iteration, which skips holes.

delete myarray[idx];

// ...

myarray.forEach(function(item, i) {
    // holes will be skipped
});

要支持IE8和更低版本的旧版浏览器,您需要为forEach()添加兼容性补丁.

To support older browsers like IE8 and lower, you'll need to add a compatibility patch for forEach().

这篇关于在具有“孔"的阵列上迭代.在JavaScript中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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