简体   繁体   English

JavaScript - 数组 - 从数组中删除元素

[英]JavaScript - Arrays - Deleting elements from an array

I've looked up arrays and how they work, looked at a lot of other stackoverflow questions on this same topic but the answer still doesn't remain clear.我查找了数组及其工作原理,查看了许多关于同一主题的其他 stackoverflow 问题,但答案仍然不明确。 How can I remove a specified element from an array?如何从数组中删除指定的元素?

I've tried:我试过了:

array.splice(5);
array.splice(i, 5);
delete array[5]; //doesn't actually delete - I know

1 of 2 things happen every time.每次都会发生 2 件事中的 1 件事。 1. The whole array is deleted with either of the first 2 methods mentioned above. 1. 使用上述前两种方法之一删除整个数组。 or 2. Everything before/after the element specified is removed.或 2. 删除指定元素之前/之后的所有内容。

For example, I had an array that contained a Clash Royale deck:例如,我有一个包含 Clash Royale 套牌的数组:

var deck = ["Barbarians", "Goblin_Barrel", "Inferno_Tower", "Fireball", "Zap", "Hog_Rider", "Spear_Goblins", "Minion_Horde"];

Then if I wanted to remove, lets say, Fireball, then I did:然后,如果我想删除,比如说,火球,那么我做了:

deck.splice("Fireball");

And the array now looked like this:数组现在看起来像这样:

deck = [];

So, to restate my question.所以,重申我的问题。 How do I remove a specified, and only the specified, element from an array?如何从数组中删除指定的且仅指定的元素?

Check the usage for splice in a JavaScript reference .检查JavaScript 参考中splice的用法。 You need to pass in the index of the thing to delete, then how many things to delete.你需要传入要删除的东西的索引,然后是要删除多少东西。

First find the index of element then remove it using splice.首先找到元素的索引,然后使用 splice 将其删除。

Find Index of element查找元素索引

var index = deck.indexOf("Fireball"); 

Now remove element using splice.现在使用 splice 删除元素。

if (index > -1) {
   deck.splice(index,1);
 }

if duplicate values exists then如果存在重复值,则

for(ind = 0 ; ind <deck.length; ind++){
    if(deck[ind]=="Fireball"){
       deck.splice(ind--,1); 
     }
}  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM