如何删除数组的匹配元素[重复]

时间:2021-05-08 21:21:44

This question already has an answer here:

这个问题在这里已有答案:

I have one array in JavaScript:

我在JavaScript中有一个数组:

['html', 'css', 'perl', 'c', 'java', 'javascript']

How can I delete "perl" element?

如何删除“perl”元素?

There has to be removing the third element. It must be to remove the element with a value of "perl".

必须删除第三个元素。必须删除值为“perl”的元素。

2 个解决方案

#1


9  

Find the index of the word, then use splice to remove it from your array.

找到单词的索引,然后使用splice将其从数组中删除。

var array = ['html', 'css', 'perl', 'c', 'java', 'javascript']  
var index = array.indexOf('perl');

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

#2


0  

if you want to just delete the value in the array and leave the spot undefined instead of having that string:

如果你只想删除数组中的值并保持点不确定而不是具有该字符串:

var arr =['html', 'css', 'perl', 'c', 'java', 'javascript'];
delete arr[arr.indexOf('perl')];

if you just want to filter that value out:

如果您只想过滤掉该值:

var arr2 = arr.filter(function(current,index,array){ return current != "perl"; } );

Just depends on what you want to do with the array and how you want to solve the problem in terms of space and how many times you want to traverse the array.

只是取决于你想对数组做什么以及你想如何在空间方面解决问题以及想要遍历数组的次数。

#1


9  

Find the index of the word, then use splice to remove it from your array.

找到单词的索引,然后使用splice将其从数组中删除。

var array = ['html', 'css', 'perl', 'c', 'java', 'javascript']  
var index = array.indexOf('perl');

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

#2


0  

if you want to just delete the value in the array and leave the spot undefined instead of having that string:

如果你只想删除数组中的值并保持点不确定而不是具有该字符串:

var arr =['html', 'css', 'perl', 'c', 'java', 'javascript'];
delete arr[arr.indexOf('perl')];

if you just want to filter that value out:

如果您只想过滤掉该值:

var arr2 = arr.filter(function(current,index,array){ return current != "perl"; } );

Just depends on what you want to do with the array and how you want to solve the problem in terms of space and how many times you want to traverse the array.

只是取决于你想对数组做什么以及你想如何在空间方面解决问题以及想要遍历数组的次数。