[英]Remove item[i] from jQuery each loop
如何在項目到達時從項目中刪除項目[i]:
$.each(items, function(i) {
// how to remove this from items
});
在這種情況下,最好不要使用$.each
。 請改用$.grep
。 這循環遍歷一個數組,與$.each
,只有一個例外。 如果從回調中返回true
,則保留該元素。 否則,它將從陣列中刪除。
您的代碼應如下所示:
items = $.grep(items, function (el, i) {
if (i === 5) { // or whatever
return false;
}
// do your normal code on el
return true; // keep the element in the array
});
還有一點需要注意: this
在$.grep
回調的上下文中設置為window
,而不是數組元素。
我猜你想要$.map
。 您可以return null
以刪除項目,而不必擔心索引可能會如何移動:
items = $.map(items, function (item, index) {
if (index < 10) return null; // Removes the first 10 elements;
return item;
});
如果要從數組中刪除元素,請使用splice()
var myArray =['a','b','c','d'];
var indexToRemove = 1;
// first argument below is the index to remove at,
//second argument is num of elements to remove
myArray.splice(indexToRemove , 1);
myArray
現在包含['a','c','d']
解決方案如下:
_.each(data, function (item, queue) {
if (somecondition) {
delete data[queue]
}
});
就像是
var indexToBeRemoved = 3; // just an illustration
$.each(items, function(i) {
if(i==indexToBeRemoved){
$(this).remove();
}
});
正如上面的@lonesomday所提到的(我根本無法在注釋中添加它) grep
用於數組,但你可以在grep
插入你的選擇器:
var items = $.grep($(".myselector", function (el, i) {
return (i===5) ? false : true;
};
這將存儲使用$(".myselector")
在“莖$(".myselector")
找到的所有元素,在第6個位置省略該項(列表為0索引,這使得“5”成為第6個元素)
雖然我通常更喜歡使用$.grep()
來過濾數組,但我有一個實例,我已經在數組上使用$.each()
來處理數據集。 在做了一些處理之后,我可以確定是否需要從數組中刪除該項:
// WARNING - DON'T DO THIS:
$.each(someArray, function(index, item) {
// Some logic here, using 'item'
if (removeItem) {
// Spice this item from the array
someArray.splice(index, 1)
}
// More logic here
});
警告:這是一個新問題! 一旦項目從數組中拼接,jQuery仍將循環顯示原始數組的長度。 例如:
var foo = [1,2,3,4,5];
$.each(foo, function(i, item) {
console.log(i + ' -- ' + item);
if (i == 3){
foo.splice(i, 1);
}
});
將輸出:
0 -- 1
1 -- 2
2 -- 3
3 -- 4
4 -- undefined
foo現在是[1, 2, 3, 5]
1,2,3,5 [1, 2, 3, 5]
。 數組中的每個項都相對於jQuery循環“移位”,我們完全錯過了元素“5”,並且循環中的最后一項是undefined
。 解決這個最好的辦法是使用反向for
循環(從去arr.length - 1
至0
)。 這將確保刪除元素不會影響循環中的下一個項目。 但是,由於這里的問題是關於$ .each,因此有一些替代方法可以解決這個問題:
1) $.grep()
循環前的數組
var someArray = $.grep(someArray, function(item) {
// Some logic here, using 'item'
return removeItem == false;
});
$.each(someArray, function(index, item) {
// More logic here
});
2)將項目推送到另一個陣列
var choiceArray = [ ];
$.each(someArray, function(index, item) {
// Some logic here, using 'item'
if (removeItem) {
// break out of this iteration and continue
return true;
}
// More logic here
// Push good items into the new array
choiceArray.push(item);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.