javascript 从数组中删除而不使用索引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9100804/
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
Remove from array without using index number
提问by Jonathan Clark
Possible Duplicate:
Remove item from array by value | JavaScript
How can I remove dogfrom the below array using Javascript. I do not want to use index if I can avoid it but rather the word dog instead.
如何使用 Javascript 从下面的数组中删除dog。如果可以避免的话,我不想使用索引,而是使用狗这个词。
["cat","dog","snake"]
回答by Claudiu
Given an array:
给定一个数组:
var arr = ["cat", "dog", "snake"];
Find its index using the indexOf
function:
使用indexOf
函数查找其索引:
var idx = arr.indexOf("dog");
Remove the element from the array by splicing it:
通过拼接从数组中移除元素:
if (idx != -1) arr.splice(idx, 1);
The resulting array will be ["cat", "snake"]
.
结果数组将为["cat", "snake"]
.
Note that if you did delete arr[idx];
instead of splicing it, arr
would be ["cat", undefined, "snake"]
, which might not be what you want.
请注意,如果您这样做delete arr[idx];
而不是拼接它,arr
将会是["cat", undefined, "snake"]
,这可能不是您想要的。