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

我想从数组y中移除2。

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


当前回答

我有一个类似的任务,我需要根据数组中对象的属性一次性删除多个对象。

所以经过几次迭代后,我最终得到:

list = $.grep(list, function (o) { return !o.IsDeleted });

其他回答

移除数组中的项目

var arr = ["jQuery", "JavaScript", "HTML", "Ajax", "Css"];
var itemtoRemove = "HTML";
arr.splice($.inArray(itemtoRemove, arr), 1);

你可以像这样使用.not函数:

var arr = [ 1 , 2 , 3 , 5 , 8];
var searchValue = 2;

var newArr = $(arr).not([searchValue]).get();

你可以使用underscore.js。这真的让事情变得简单。

在你的例子中,你需要写的所有代码都是-

_.without([1,2,3], 2);

结果是[1,3]。

它减少了你编写的代码。

只是把Sarfraz的答案加上去,很惊讶没有人把它变成一个函数。

如果在数组中不止一次有相同的值,则使用.filter方法使用ddagsan的答案。

函数arrayremovevalue(数组,removeValue){ var newArray = jQuery。grep(数组,函数(值){返回值!= removeValue;}); 返回newArray; } var promoItems = [1,2,3,4]; promoItems = arrayremoveeval (promoItems, 3) console.log (promoItems); promoItems = arrayremoveeval (promoItems, 3);//不移除任何东西 console.log (promoItems); < script src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js " > < /脚本>

使用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