清除方法从javascript数组中删除元素(使用jQuery,coffeescript) [英] Clean way to remove element from javascript array (with jQuery, coffeescript)

查看:121
本文介绍了清除方法从javascript数组中删除元素(使用jQuery,coffeescript)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多问题,尤其是:
jQuery版本的数组包含 a解决方案与拼接方法和更多。

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

使用javascript,jQuery和coffeescript的强大功能,从javascript数组中删除元素的最简洁的方法是什么?我们不知道提前索引。在代码中:

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:

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

没有一个很好的内置方法,什么是干净扩展javascript数组以支持这种方法的方式?如果它有帮助,我真的使用数组作为集。解决方案将理想地工作在coffeescript与jQuery支持。

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.

推荐答案

CoffeeScript:

CoffeeScript:

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

只需在位置 t ,找到其中 e (如果实际发现 t> -1 )的索引。 Coffeescript将其翻译为:

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

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

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

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

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

p>

which translates into:

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

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

Or doing the same without jQuery's grep:

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

可翻译成:

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

这篇关于清除方法从javascript数组中删除元素(使用jQuery,coffeescript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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