jQuery 如何从jquery中的数组对象中删除项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9361371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove item from array object in jquery
提问by Kalaivani
How to remove item from jquery array object.
如何从 jquery 数组对象中删除项目。
I used splice method as follows. But it slice next item of array[i].
我使用拼接方法如下。但它切片数组 [i] 的下一项。
$.each(array, function (i, item) {
var user = array[i];
jQuery.each(array2, function (index, idata) {
debugger
if (idata.Id == user.UserId) {
tempFlag = 1;
return false; // this stops the each
}
else {
tempFlag = 0;
}
});
if (tempFlag != 1) {
//removes an item here
array.splice(user, 1);
}
})
Can anyone tell me where i am wrong here?
谁能告诉我我错在哪里?
回答by Anand Soni
You should try this to remove element from array in jQuery:
您应该尝试从 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);
Check this Link for more : Clean way to remove element from javascript array (with jQuery, coffeescript)
查看此链接了解更多信息:Clean way to remove element from javascript array (with jQuery, coffeescript)
回答by Guffa
You are using the value in user
as index, i.e. array[i]
, instead of the value i
.
您正在使用中的值user
作为索引,即array[i]
,而不是值i
。
$.each(array, function (i, item) {
var user = array[i];
jQuery.each(array2, function (index, idata) {
debugger
if (idata.Id == user.UserId) {
tempFlag = 1;
return false; // this stops the each
} else {
tempFlag = 0;
}
});
if (tempFlag != 1) {
//removes an item here
array.splice(i, 1);
}
});
You may get problems from removing items from the array that you are currently looping, though...
但是,从当前循环的数组中删除项目可能会出现问题......