2013-04-28 52 views
3

我想刪除數組的元素並調整數組大小。
我用:刪除數組中的元素並調整其大小

selectedproducts=jQuery.grep(selectedproducts, function(value) { 
    return value != thisID; 
}); 

selectedproducts的大小保持不變。

我用:

console.log(selectedproducts.length); 

後每刪除打印selectedproductslenght,但它不會改變。

請問有這個功能嗎?

編輯:

我有5個元素的數組。

我得到使用Felix控制檯什麼答案每刪除後:

Size:4 
["Celery", "Tomatoes", undefined, "Carrots"] 
Size:3 
["Celery", undefined, "Carrots"] 
Size:2 
[undefined, "Carrots"] 
Size:1 
[undefined] 

編輯2:

我試圖vishakvkt的答案,並能正常工作。

我在控制檯中看到什麼:

Size:4 
["Beans", "Avocado", "Snow Peas", "Tomatoes"] 
Size:3 
["Avocado", "Snow Peas", "Tomatoes"] 
Size:2 
["Avocado", "Snow Peas"] 
Size:1 
["Snow Peas"] 
Size:0 
[] 
+2

'$ .grep'爲我工作得很好:HTTP:// jsfiddle.net/J4cVY/。 – 2013-04-28 10:36:25

+1

[可從javascript數組中刪除特定元素?](http://stackoverflow.com/questions/5767325/remove-specific-element-from-a-javascript-array) – 2013-04-28 10:38:11

回答

6

你應該使用Array.splice(position_you_want_to_remove, number_of_items_to_remove)

所以,如果你有

var a = [1, 2, 3]; 
    a.splice(0, 1); // remove one element, beginning at position 0 of the array 
    console.log(a); // this will print [2,3] 
+3

鏈接到文檔:https:/ /developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/splice – 2013-04-28 10:40:24

相關問題