JavaScript数组搜索并删除字符串? [英] Javascript array search and remove string?
本文介绍了JavaScript数组搜索并删除字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有:
var array = new Array();
array.push("A");
array.push("B");
array.push("C");
我希望能够做一些事情,如:
I want to be able to do something like:
array.remove(B);
但没有删除功能。我如何做到这一点?
but there is no remove function. How do I accomplish this?
推荐答案
遍历列表以相反的顺序,并使用<$c$c>.splice$c$c>方法。
Loop through the list in reverse order, and use the .splice
method.
var array = ['A', 'B', 'C']; // Test
var search_term = 'B';
for (var i=array.length-1; i>=0; i--) {
if (array[i] === search_term) {
array.splice(i, 1);
// break; //<-- Uncomment if only the first term has to be removed
}
}
相反的顺序很重要,当全部搜索词的出现已被删除。否则,计数器会增加,你会跳过元素。
The reverse order is important when all occurrences of the search term has to be removed. Otherwise, the counter will increase, and you will skip elements.
当只有第一次出现已经被删除,下面也将工作:
When only the first occurrence has to be removed, the following will also work:
var index = array.indexOf(search_term); // <-- Not supported in <IE9
if (index !== -1) {
array.splice(index, 1);
}
这篇关于JavaScript数组搜索并删除字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文