如何通过值删除阵列的多个项目? [英] How to delete multiple items of an array by value?

查看:81
本文介绍了如何通过值删除阵列的多个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让的removeAll()的功能,这将删除数组中的所有元素与特定值(不是索引)。

I am trying to make a removeAll() function, which will remove all elements of an array with that particular value (not index).

最棘手的部分是,当我们进行任何更改的循环中,指标趋于走动(使它很难使其工作像我们想要的),并重新启动我们每一个变化的时间循环是对大非常低效数组。

The tricky part comes when we make any change to the loop, the indexes tend to move around (making it very hard to make it work like we want) and, restarting the loop every time we make changes is very inefficient on big arrays.

到目前为止,我写我自己 arr.indexOf 功能(用于较老的IE支持),它看起来像这样:

So far, I wrote my own arr.indexOf function (for older IE support), it looks like this:

function arrFind(val, arr) {
    for (var i = 0, len = arr.length, rtn = -1; i < len; i++) {
        if (arr[i] === val) {
            return i;
        }
    }
    return -1;
}

这是很容易去除这样的内容:

It is easy to remove elements like this:

var myarray = [0, 1, 2, 3, 4];
var tofind = 2;

var stored_index = arrFind(tofind, myarray);
if (stored_index != -1) {
    myarray.splice(stored_index, 1);
}

alert(myarray.join(",")); //0,1,3,4

不过,正如我刚才所指出的,这样做而循环时,我们遇到麻烦。

However, as I pointed out earlier, when doing this while looping, we get in trouble.

如何正确地删除阵列项目,而通过它循环的任何想法?

推荐答案

循环以相反的顺序或建立与不被删除的项的新数组。

Loop in reverse order or build a new array with the items that are not to be removed.

这篇关于如何通过值删除阵列的多个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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