如何在 JavaScript 中删除数组中的特定元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10940607/
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
How to remove a specific element in array in JavaScript
提问by Adham
If I have array, for example:
如果我有数组,例如:
a = ["a", "b", "c"]
I need something like
我需要类似的东西
a.remove("a");
How can I do this?
我怎样才能做到这一点?
采纳答案by Danilo Valente
var newArray = [];
var a=["a","b","c"];
for(var i=0;i<a.length;i++)
if(a[i]!=="a")
newArray.push(a[i]);
As of newer versions of JavaScript:
从较新版本的 JavaScript 开始:
var a = ["a","b","c"];
var newArray = a.filter(e => e !== "a");
回答by georg
remove = function(ary, elem) {
var i = ary.indexOf(elem);
if (i >= 0) ary.splice(i, 1);
return ary;
}
provided your target browser suppports array.indexOf
, otherwise use the fallback code on that page.
提供您的目标浏览器支持array.indexOf
,否则使用该页面上的回退代码。
If you need to remove allequal elements, use filter
as Rocket suggested:
如果您需要删除所有相等的元素,请filter
按照 Rocket 的建议使用:
removeAll = function(ary, elem) {
return ary.filter(function(e) { return e != elem });
}
回答by Rocket Hazmat
回答by Milinda Bandara
I came up with a simple solution to omit the necessary element from the array:
我想出了一个简单的解决方案来省略数组中的必要元素:
<script>
function myFunction()
{
var fruits = ["One", "Two", "Three", "Four"];
<!-- To drop the element "Three"-->
<!-- splice(elementid, number_of_element_remove) -->
fruits.splice(2, 1);
var x = document.getElementById("demo");
x.innerHTML = fruits;
}
</script>
回答by Siddhartha
let xx = ['a','a','b','c']; // Array
let elementToRemove = 'a'; // Element to remove
xx =xx.filter((x) => x != elementToRemove) // xx will contain all elements except 'a'
回答by Jerome WAGNER
If you don't mind the additional payload (around 4 kB minified and gzipped) you could use the without function of the Underscore.js library:
如果你不介意额外的负载(大约 4 kB 压缩和压缩),你可以使用Underscore.js 库的without 功能:
_.without(["a", "b", "c"], "a");
Underscore.jswould give you this function + a lot of very convenient functions.
Underscore.js会给你这个功能+很多非常方便的功能。