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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 05:35:56  来源:igfitidea点击:

Remove from array without using index number

javascript

提问by Jonathan Clark

Possible Duplicate:
Remove item from array by value | JavaScript

可能重复:
按值从数组中删除项目 | 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 indexOffunction:

使用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, arrwould be ["cat", undefined, "snake"], which might not be what you want.

请注意,如果您这样做delete arr[idx];而不是拼接它,arr将会是["cat", undefined, "snake"],这可能不是您想要的。

Source

来源