2012-02-20 130 views
1

如何從jquery數組對象中刪除項目。如何從jquery中的數組對象中刪除項目

我使用拼接方法如下。但它切片數組[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); 
    } 
}) 

有誰能告訴我我在哪裏錯了嗎?

回答

4

您正在使用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); 
    } 
}); 

你可以從去除您當前循環,雖然數組項獲得問題...

6

你應該試試這個從陣列中的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); 

檢查此鏈接以瞭解更多信息:Clean way to remove element from javascript array (with jQuery, coffeescript)

+0

這是乾淨的,但不適用於當前形式的問題,因爲代碼不僅僅是查找數組中的項目,而是尋找項目s在另一個數組中包含項目,其中一個屬性對應於該項目的屬性。 – Guffa 2012-02-20 12:59:25

+0

但它幫助了我,謝謝。 – Ankur 2013-03-13 04:17:27