jquery version of array.contains

前端 未结 4 1365
我在风中等你
我在风中等你 2021-01-30 12:26

Can jQuery test an array for the presence of an object (either as part of the core functionality or via an avaible plugin)?

Also, I\'m looking for something like a

4条回答
  •  一生所求
    2021-01-30 13:07

    This is not jQuery, but in one line you can add a handy 'contains' method to arrays. I find this helps with readability (especially for python folk).

    Array.prototype.contains = function(a){ return this.indexOf(a) != -1 }
    

    example usage

     > var a = [1,2,3]
     > a.contains(1)
    true
     > a.contains(4)
    false
    

    Similarly for remove

    Array.prototype.remove = function(a){if (this.contains(a)){ this.splice(this.indexOf(a),1)}; return this}
    
    > var a = [1,2,3]
    > a.remove(2)
    [1,3]
    

    Or, if you want it to return the thing removed rather than the altered array, then

    Array.prototype.remove = function(a){if (this.contains(a)){ return this.splice(this.indexOf(a),1)}}
    
    > var a = [1,2,3]
    > a.remove(2)
    [2]
    > a
    [1,3]
    

提交回复
热议问题