Javascript Jquery从数组中删除元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6234269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery remove element from array
提问by CyberJunkie
This should be fun to solve :)
这应该很有趣解决:)
In a text field I have the value Apple,Peach,Banana
.
在文本字段中,我有 value Apple,Peach,Banana
。
Using Jquery I created an array from that CSV.
使用 Jquery 我从那个 CSV 创建了一个数组。
In HTML I have a list of the fruits with a "remove" option next to each one. When I click "remove" I want to remove the corresponding fruit from the list and the text field.
在 HTML 中,我有一个水果列表,每个水果旁边都有一个“删除”选项。当我单击“删除”时,我想从列表和文本字段中删除相应的水果。
I'm missing one function that will remove fruits from the array. What function should I use?
我缺少一个可以从数组中删除水果的函数。我应该使用什么功能?
回答by Tim
You should use JavaScript Splice
你应该使用JavaScript Splice
fruits_array.splice(fruit_index,1);
You also need to change:
您还需要更改:
$('#fruits').val(skills_array.join(','));
to $('#fruits').val(fruits_array.join(','));
$('#fruits').val(skills_array.join(','));
到 $('#fruits').val(fruits_array.join(','));
回答by kennebec
var A=['Apple','Peach','Banana'];
A.splice(1,1)
// removes 1 item starting at index[1]
// returns ['Peach'];
回答by Doug
The accepted solution is correct, but it doesn't mention that you shouldn't use indexOf to get the fruit_index to remove, because IndexOf not Supported in IE8 Browser
接受的解决方案是正确的,但它没有提到您不应该使用 indexOf 来删除fruit_index,因为IE8 浏览器不支持 IndexOf
You should use:
你应该使用:
fruits_array.splice($.inArray('Peach', fruits_array), 1);