2013-04-28 57 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

相关问题