循环使用中多次出现的数组中删除元素
问题描述:
我要在具有多个事件与函数的数组中删除元素。
I want to remove an element in an array with multiple occurrences with a function.
var array=["hello","hello","world",1,"world"];
function removeItem(item){
for(i in array){
if(array[i]==item) array.splice(i,1);
}
}
removeItem("world");
//Return hello,hello,1
removeItem("hello");
//Return hello,world,1,world
这个循环,当它在序列重复两次不删除元素,只删除其中的一个。
This loop doesn't remove the element when it repeats twice in sequence, only removes one of them.
为什么?
答
您有一个内置的函数叫做filter$c$c>该过滤器基于一个predicate(的条件)的数组。
You have a built in function called filter
that filters an array based on a predicate (a condition).
这不会改变原来的数组,但返回一个新过滤的。
It doesn't alter the original array but returns a new filtered one.
var array=["hello","hello","world",1,"world"];
var filtered = array.filter(function(element){
return element !== "hello";
}); // filtered contains no occurrences of hello
您可以将其解压缩到一个功能:
You can extract it to a function:
function without(array, what){
return array.filter(function(el){
return element !== what;
});
}
不过,原来的过滤器似乎EX pressive足够了。
However, the original filter seems expressive enough.
Here是它的文档链接
您原有的功能有几个问题:
Your original function has a few issues:
- 它重复使用
为中...
循环具有迭代顺序上没有保证的阵列。此外,不要用它来遍历数组 - preFER正常的。 ..
环或.forEach
- 您正在迭代与差一错误让你跳跃上的下一个项目,因为你们都删除元素和进步数组的数组。
- It iterates the array using a
for... in
loop which has no guarantee on the iteration order. Also, don't use it to iterate through arrays - prefer a normalfor...
loop or a.forEach
- You're iterating an array with an off-by-one error so you're skipping on the next item since you're both removing the element and progressing the array.