删除数组的元素并调整其大小 [英] remove an element of an array and resize it

查看:123
本文介绍了删除数组的元素并调整其大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想删除数组的元素并调整数组的大小.
我用过:

I want to remove an element of an array and resize the size of the array.
I used:

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

,但selectedproducts的大小保持不变.

我使用:

console.log(selectedproducts.length);

要在每次删除后打印selectedproductslenght,但不会更改.

To print the lenght of selectedproducts after every delete, but it doesn't change.

的问题?

我有一个包含5个元素的数组.

I had an Array with 5 elements.

每次删除后,我使用 Felix 的答案在控制台中得到的内容:

What I get in the console using Felix's answer after every remove:

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

我尝试了 vishakvkt 的答案,并且效果很好.

I tried vishakvkt's answer and works fine.

我在控制台中得到的内容:

What I get in the console:

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]

这篇关于删除数组的元素并调整其大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆