删除数组的元素并调整其大小
我想删除数组的元素并调整数组的大小。
我用了:
selectedproducts=jQuery.grep(selectedproducts, function(value) { return value != thisID; });
但selectedproducts
的大小保持不变。
我用:
console.log(selectedproducts.length);
要在每次删除后打印selectedproducts
的lenght
,但不会更改。
有没有javascript或jquery中的函数来做到这一点?
编辑:
我有一个包含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 []
你应该使用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]