Programing

자바 스크립트 배열에서 요소를 제거하는 깨끗한 방법 (jQuery, coffeescript 사용)

lottogame 2020. 12. 7. 07:41
반응형

자바 스크립트 배열에서 요소를 제거하는 깨끗한 방법 (jQuery, coffeescript 사용)


이것에 대한 많은 질문이 있습니다 . 배열의 jQuery 버전에는 , splice 메서드 가 포함 된 솔루션 등이 포함 됩니다. 그러나 그것들은 모두 복잡하고 성가신 것처럼 보입니다.

자바 스크립트, jQuery 및 coffeescript의 결합 된 기능을 사용하여 자바 스크립트 배열에서 요소를 제거하는 가장 깨끗한 방법은 무엇입니까? 우리는 색인을 미리 알지 못합니다. 코드에서 :

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

좋은 내장 메서드가 실패하면 이러한 메서드를 지원하기 위해 자바 스크립트 배열을 확장하는 깨끗한 방법은 무엇입니까? 도움이된다면 실제로 배열을 세트로 사용하고 있습니다. 솔루션은 jQuery 지원을 통해 coffeescript에서 이상적으로 잘 작동합니다. 또한 속도에 대해서는 신경 쓰지 않고 명확하고 간단한 코드를 우선시합니다.


CoffeeScript :

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

위치에있는 요소 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);
    }
};

그리고 일치하는 모든 요소를 ​​제거하고 CoffeeScript 및 jQuery를 사용하여 새 배열을 반환하려면 :

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

다음과 같이 번역됩니다.

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

또는 jQuery의 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;
};

바닐라 자바 ​​스크립트 사용 :

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

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

이것은 jQuery를 사용하면 정말 쉽습니다.

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

메모:

splice제거 된 요소를 반환하므로 myArray = myArray.splice(). myArray.splice(index,1)"배열에서 인덱스의 배열 요소 제거"를 의미 'index'합니다.

$.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:

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

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

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

or in js:

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

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

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:

array.filter (item) -> item isnt match

Filter is not supported in legacy browsers, but Mozilla provides a polyfill that 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.

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.

There you have it, no libraries needed!


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

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:

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:

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!

참고URL : https://stackoverflow.com/questions/4825812/clean-way-to-remove-element-from-javascript-array-with-jquery-coffeescript

반응형