我有一个这样的数组:var y = [1,2,3];

我想从数组y中移除2。

如何使用jQuery从数组中删除一个特定的值?我尝试过pop(),但它总是删除最后一个元素。


当前回答

/** SUBTRACT ARRAYS **/

function subtractarrays(array1, array2){
    var difference = [];
    for( var i = 0; i < array1.length; i++ ) {
        if( $.inArray( array1[i], array2 ) == -1 ) {
                difference.push(array1[i]);
        }
    }
return difference;
}  

然后可以在代码中的任何地方调用该函数。

var I_like    = ["love", "sex", "food"];
var she_likes = ["love", "food"];

alert( "what I like and she does't like is: " + subtractarrays( I_like, she_likes ) ); //returns "Naughty :P"!

这在所有情况下都有效,并避免了上述方法中的问题。希望有帮助!

其他回答

使用JavaScript安全地从数组中删除2:

// Define polyfill for browsers that don't natively support Array.indexOf()
if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(searchElement, fromIndex) {
    var k;
    if (this===null) {
      throw new TypeError('"this" is null or not defined');
    }
    var O = Object(this),
      len = O.length >>> 0;
    if (len===0) return -1;
    var n = +fromIndex || 0;
    if (Math.abs(n)===Infinity) n = 0;
    if (n >= len) return -1;
    k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
    while (k < len) {
      if (k in O && O[k]===searchElement) return k;
      ++k;
    }
    return -1;
  };
}

// Remove first instance of 2 from array
if (y.indexOf(2) > -1) {
  y.splice(y.indexOf(2), 1);
}

/* To remove all instances of 2 from array, change 'if' to 'while':
while (y.indexOf(2) > -1) {
  y.splice(y.indexOf(2), 1);
}
*/

console.log(y);  // Returns [1, 3]

Polyfill来源:Mozilla

在Javascript中没有本机的方法来做到这一点。您可以使用一个库或编写一个小函数来代替:http://ejohn.org/blog/javascript-array-remove/

不是jQuery的方式,但是… 为什么不用更简单的方法呢?从下面的数组中删除'c'

var a = ['a','b','c','d']
a.splice(a.indexOf('c'),1);
>["c"]
a
["a", "b", "d"]

你也可以使用:(给自己的提示:不要修改你不拥有的对象)

Array.prototype.remove = function(v) { this.splice(this.indexOf(v) == -1 ? this.length : this.indexOf(v), 1); }
var a = ['a','b','c'];
a.remove('c'); //value of "a" is now ['a','b']

添加是simplera.push('c')

试试这个,对我有用

_clientsSelected = ["10", "30", "12"];
function (removeItem) {
console.log(removeItem);
   _clientsSelected.splice($.inArray(removeItem, _clientsSelected), 1);
   console.log(_clientsSelected);
`enter code here`},

我将用pick_and_remove()函数扩展Array类,如下所示:

var ArrayInstanceExtensions = {
    pick_and_remove: function(index){
        var picked_element = this[index];
        this.splice(index,1);
        return picked_element;
    } 
};
$.extend(Array.prototype, ArrayInstanceExtensions);

虽然看起来有点啰嗦,但现在可以在任何需要的数组上调用pick_and_remove() !

用法:

array = [4,5,6]           //=> [4,5,6]
array.pick_and_remove(1); //=> 5
array;                    //=> [4,6]

你可以在《口袋妖怪》主题的动作中看到这一切。