javascript - 在条件下删除数组元素 [英] javascript - remove array element on condition

查看:117
本文介绍了javascript - 在条件下删除数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在javascript中实现一个方法,删除清除某个条件的数组的所有元素。 (最好不使用jQuery)

I was wondering how I'd go about implementing a method in javascript that removes all elements of an array that clear a certain condition. (Preferably without using jQuery)

前。

ar = [ 1, 2, 3, 4 ];
ar.removeIf( function(item, idx) {
    return item > 3;
});

以上内容将遍历数组中的每个项目并删除所有对于条件返回true (在示例中,item> 3)。

The above would go through each item in the array and remove all those that return true for the condition (in the example, item > 3).

我刚开始使用javascript并且想知道是否有人知道一种简短有效的方法来完成这项工作。

I'm just starting out in javascript and was wondering if anyone knew of a short efficient way to get this done.

- 更新 -

如果条件也适用于对象属性也会很棒。

It would also be great if the condition could work on object properties as well.

Ex。

ar = [ {num:1, str:"a"}, {num:2, str:"b"}, {num:3, str:"c"} ];
ar.removeIf( function(item, idx) {
    return item.str == "c";
});

如果 item.str ==c,该项目将被删除

- update2 -

它如果指数条件也可以有效,那就太好了。

It would be nice if index conditions could work as well.

前。

ar = [ {num:1, str:"a"}, {num:2, str:"b"}, {num:3, str:"c"} ];
ar.removeIf( function(item, idx) {
    return idx == 2;
});


推荐答案

您可以将自己的方法添加到数组做类似的事情,如果 filter 不适合你。

You could add your own method to Array that does something similar, if filter does not work for you.

Array.prototype.removeIf = function(callback) {
    var i = 0;
    while (i < this.length) {
        if (callback(this[i], i)) {
            this.splice(i, 1);
        }
        else {
            ++i;
        }
    }
};

对我而言,这是JavaScript最酷的功能之一。伊恩指出了一种更有效的方法来做同样的事情。考虑到它是JavaScript,每一点都有帮助:

To me, that's one of the coolest features of JavaScript. Ian pointed out a more efficient way to do the same thing. Considering that it's JavaScript, every bit helps:

Array.prototype.removeIf = function(callback) {
    var i = this.length;
    while (i--) {
        if (callback(this[i], i)) {
            this.splice(i, 1);
        }
    }
};

这避免了甚至担心更新长度或抓住下一个项目,因为你的工作方式是向左而不是正确。

This avoids the need to even worry about the updating length or catching the next item, as you work your way left rather than right.

这篇关于javascript - 在条件下删除数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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