简体   繁体   English

清除从javascript数组中删除元素的方法(使用jQuery,coffeescript)

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

There are many questions about this, not least: jQuery version of array contains , a solution with the splice method and many more. 关于这一点有很多问题,尤其是: 数组的jQuery版本包含splice方法的解决方案等等。 However, they all seem complicated and annoying. 然而,它们看起来既复杂又令人讨厌。

With the combined powers of javascript, jQuery and coffeescript, what is the very cleanest way to remove an element from a javascript array? 利用javascript,jQuery和coffeescript的强大功能,从javascript数组中删除元素的最简洁方法是什么? We don't know the index in advance. 我们事先并不知道该指数。 In code: 在代码中:

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? 如果没有一个好的内置方法,那么扩展javascript数组以支持这种方法的干净方法是什么? If it helps, I'm really using arrays as sets. 如果它有帮助,我真的使用数组作为集合。 Solutions will ideally work nicely in coffeescript with jQuery support. 解决方案理想情况下可以在coffeescript中使用jQuery支持。 Also, I couldn't care less about speed, but instead prioritize clear, simple code. 此外,我不关心速度,而是优先考虑清晰,简单的代码。

CoffeeScript: CoffeeScript的:

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

Which simply splices out the element at position t , the index where e was found (if it was actually found t > -1 ). 这简单地拼接了位置t处的元素,即找到e的索引(如果实际发现t > -1 )。 Coffeescript translates this to: 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;
};

Using vanilla Javascript: 使用vanilla 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);

This is really easy with jQuery: 使用jQuery非常简单:

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

Notes: 笔记:

splice returns the elements that were removed, so don't do myArray = myArray.splice() . splice返回已删除的元素,因此不要执行myArray = myArray.splice() myArray.splice(index,1) means "remove the array element at index 'index' from the array". myArray.splice(index,1)表示“从数组中删除索引'index'处的数组元素”。

$.inArray returns the index in the array of the value you're looking for, or -1 if the value isn't in the array. $.inArray返回您要查找的值的数组中的索引,如果该值不在数组中,则返回-1。

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 @

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 polyfill that adheres to the ECMA standard. 过滤器是不是在传统的浏览器支持,但Mozilla的提供了一个填充工具附着在ECMA标准。 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. 我认为这是一种非常安全的方法,因为您只是将旧浏览器引入现代标准,并且您没有在您的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方法,但我认为你主要是要求一个库方法,因为你不知道一个干净的javascript方法。

There you have it, no libraries needed! 你有它,不需要图书馆!

if you are also using CoffeeScript creator's underscore.js library, 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; });

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);
  }};

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 new array; 这里可能存在性能问题,因为您在技术上导致变量引用数组; 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! 干杯!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM