我有一个这样的数组:var y = [1,2,3];
我想从数组y中移除2。
如何使用jQuery从数组中删除一个特定的值?我尝试过pop(),但它总是删除最后一个元素。
我有一个这样的数组:var y = [1,2,3];
我想从数组y中移除2。
如何使用jQuery从数组中删除一个特定的值?我尝试过pop(),但它总是删除最后一个元素。
当前回答
一个工作的JSFIDDLE
你可以这样做:
var y = [1, 2, 2, 3, 2]
var removeItem = 2;
y = jQuery.grep(y, function(value) {
return value != removeItem;
});
结果:
[1, 3]
http://snipplr.com/view/14381/remove-item-from-array-with-jquery/
其他回答
你可以像这样使用.not函数:
var arr = [ 1 , 2 , 3 , 5 , 8];
var searchValue = 2;
var newArr = $(arr).not([searchValue]).get();
只是把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 " > < /脚本>
我有一个类似的任务,我需要根据数组中对象的属性一次性删除多个对象。
所以经过几次迭代后,我最终得到:
list = $.grep(list, function (o) { return !o.IsDeleted });
不是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')
//This prototype function allows you to remove even array from array
Array.prototype.remove = function(x) {
var i;
for(i in this){
if(this[i].toString() == x.toString()){
this.splice(i,1)
}
}
}
使用实例
var arr = [1,2,[1,1], 'abc'];
arr.remove([1,1]);
console.log(arr) //[1, 2, 'abc']
var arr = [1,2,[1,1], 'abc'];
arr.remove(1);
console.log(arr) //[2, [1,1], 'abc']
var arr = [1,2,[1,1], 'abc'];
arr.remove('abc');
console.log(arr) //[1, 2, [1,1]]
要使用这个原型函数,您需要将其粘贴到代码中。 然后你可以将它应用到任何带有“点符号”的数组:
someArr.remove('elem1')