我想删除数组的一个元素并调整数组的大小。
我用过:
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]
关于javascript - 删除数组的一个元素并调整它的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16261973/