从 javascript 数组中删除元素的干净方法(使用 jQuery、coffeescript)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4825812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:17:50  来源:igfitidea点击:

Clean way to remove element from javascript array (with jQuery, coffeescript)

javascriptjquerycoffeescript

提问by Peter

There are many questions about this, not least: jQuery version of array contains, a solution with the splice methodand many more. However, they all seem complicated and annoying.

关于这个有很多问题,尤其是: jQuery 版本的 array contains一个带有 splice 方法的解决方案等等。然而,它们看起来都很复杂和烦人。

With the combined powers of javascript, jQuery and coffeescript, what is the very cleanest way to remove an element from a javascript array? We don't know the index in advance. In code:

结合 javascript、jQuery 和 coffeescript 的强大功能,从 javascript 数组中删除元素的最干净的方法是什么?我们事先不知道索引。在代码中:

a = [4,8,2,3]
a.remove(8)     # a is now [4,2,3]

Failing a good built-in method, what is a clean way of extending javascript arrays to support such a method? If it helps, I'm really using arrays as sets. Solutions will ideally work nicely in coffeescript with jQuery support. Also, I couldn't care less about speed, but instead prioritize clear, simple code.

没有一个好的内置方法,扩展 javascript 数组以支持这种方法的干净方法是什么?如果有帮助,我真的将数组用作集合。理想情况下,解决方案将在具有 jQuery 支持的 coffeescript 中很好地工作。此外,我不太在意速度,而是优先考虑清晰、简单的代码。

回答by Amir

CoffeeScript:

咖啡脚本:

Array::remove = (e) -> @[t..t] = [] if (t = @indexOf(e)) > -1

Which simply splices out the element at position t, the index where ewas found (if it was actually found t > -1). Coffeescript translates this to:

它简单地拼接出位置处的元素t,即e找到的索引(如果确实找到了t > -1)。Coffeescript 将其翻译为:

Array.prototype.remove = function(e) {
    var t, _ref;
    if ((t = this.indexOf(e)) > -1) {
        return ([].splice.apply(this, [t, t - t + 1].concat(_ref = [])), _ref);
    }
};

And if you want to remove all matching elements, and return a new array, using CoffeeScript and jQuery:

如果你想删除所有匹配的元素,并返回一个新数组,使用 CoffeeScript 和 jQuery:

Array::remove = (v) -> $.grep @,(e)->e!=v

which translates into:

翻译成:

Array.prototype.remove = function(v) {
    return $.grep(this, function(e) {
        return e !== v;
    });
};

Or doing the same without jQuery's grep:

或者在没有 jQuery 的 grep 的情况下做同样的事情:

Array::filterOutValue = (v) -> x for x in @ when x!=v

which translates to:

这意味着:

Array.prototype.filterOutValue = function(v) {
    var x, _i, _len, _results;
    _results = [];
    for (_i = 0, _len = this.length; _i < _len; _i++) {
        x = this[_i];
        if (x !== v) {
            _results.push(x);
        }
    }
    return _results;
};

回答by jAndy

Using vanilla Javascript:

使用香草 Javascript:

Array.prototype.remove = function(elem) {
    var match = -1;

    while( (match = this.indexOf(elem)) > -1 ) {
        this.splice(match, 1);
    }
};

var a = [4, 8, 2, 3];

a.remove(8);

Only jQuery:

只有jQuery:

jQuery.removeFromArray = function(value, arr) {
    return jQuery.grep(arr, function(elem, index) {
        return elem !== value;
    });
};

var a = [4, 8, 2, 3];

a = jQuery.removeFromArray(8, a);

回答by adavea

This is really easy with jQuery:

使用 jQuery 这真的很容易:

var index = $.inArray("value", myArray);
if(index != -1)
{
  myArray.splice(index, 1);
}

Notes:

笔记:

splicereturns the elements that were removed, so don't do myArray = myArray.splice(). myArray.splice(index,1)means "remove the array element at index 'index'from the array".

splice返回被删除的元素,所以不要这样做myArray = myArray.splice()myArray.splice(index,1)表示“从数组中删除索引'index'处的数组元素”。

$.inArrayreturns the index in the array of the value you're looking for, or -1 if the value isn't in the array.

$.inArray返回您要查找的值在数组中的索引,如果该值不在数组中,则返回 -1。

回答by Domenic

This seems pretty clean and understandable; unlike other answers, it takes into account the possibility of an element showing up more than once.

这看起来很干净并且可以理解;与其他答案不同,它考虑了一个元素出现不止一次的可能性。

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

In CoffeeScript:

在 CoffeeScript 中:

Array::remove = (value) ->
    i = 0
    while i < @length
        if @[i] == value
            @splice i, 1
        else
            ++i
    return @

回答by georgedyer

if you are also using CoffeeScript creator's underscore.jslibrary, here's a one-liner that will work nicely:

如果您还使用 CoffeeScript creator 的underscore.js库,这里有一个可以很好地工作的单行:

a = _(a).reject (v)-> v is e

or in js:

或在 js 中:

a = _(a).reject(function(v) { return v == e; });

回答by TimE

Although you are asking for a clean approach using Coffeescript or jQuery, I find the cleanest approach is using the vanilla javascript method filter:

虽然您要求使用 Coffeescript 或 jQuery 的干净方法,但我发现最干净的方法是使用 vanilla javascript 方法过滤器

array.filter(function (item) { return item !== match });

It looks cleaner in coffeescript but this translates to the exact same javascript, so I only consider it a visual difference, and not an advanced feature of coffeescript:

在 coffeescript 中它看起来更干净,但这转化为完全相同的 javascript,所以我只认为它是一种视觉差异,而不是 coffeescript 的高级功能:

array.filter (item) -> item isnt match

Filter is not supported in legacy browsers, but Mozilla provides a polyfillthat adheres to the ECMA standard. I think this is a perfectly safe approach because you are only bringing old browsers to modern standards, and you are not inventing any new functionality in your polyfill.

过滤器是不是在传统的浏览器支持,但Mozilla的提供了一个填充工具附着在ECMA标准。我认为这是一种非常安全的方法,因为您只是将旧浏览器带到现代标准,并且您并没有在 polyfill 中发明任何新功能。

Sorry if you were specifically looking for a jQuery or Coffeescript only method, but I think you were mainly asking for a library method because you were unaware of a clean javascript only method.

抱歉,如果您是专门寻找 jQuery 或 Coffeescript only 方法,但我认为您主要是要求一个库方法,因为您不知道一个干净的 javascript only 方法。

There you have it, no libraries needed!

你有它,不需要图书馆!

回答by Durant Schoon

This is just a slight change to Amir's awesome solution:

这只是对Amir 很棒的解决方案的一个小改动:

Array::remove = (e) -> @splice(t,1)[0] if (t = @indexOf(e)) > -1

which returns the element iff the list has it, so you can do something like:

它返回元素如果列表有它,所以你可以做这样的事情:

do_something 100 if a.remove(100)

The remove coffee script translates to this javascript:

删除咖啡脚本转换为这个 javascript:

Array.prototype.remove = function(e) {
  var t, _ref;
  if ((t = this.indexOf(e)) > -1) {
    return ([].splice.apply(this, [t, t - t + 1].concat(_ref = [])), _ref);
  }};

回答by Mike Marcacci

You might just try jQuery's grep utility:

您可以尝试使用 jQuery 的 grep 实用程序:

a = [4,8,2,3]
$.grep(a,function(v){return v!=8;})

There may be a performance issue here, as you're technically causing the variable to reference a newarray; you're not really modifying the original one. Assuming the original isn't referenced somewhere else, the garbage collector should take or this pretty quickly. This has never been an issue for me, but others might know better. Cheers!

这里可能存在性能问题,因为您在技术上导致变量引用数组;你并没有真正修改原始的。假设原始文件没有在其他地方被引用,垃圾收集器应该很快接受或这样做。这对我来说从来都不是问题,但其他人可能更清楚。干杯!