javascript 如何从数组中删除每第二个和第三个元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4308303/
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
Howto delete every second and third element from an array?
提问by Bob
I want to delete every second and third element from an array in Javascript.
我想从 Javascript 中的数组中删除每第二个和第三个元素。
My array looks like this:
我的数组看起来像这样:
var fruits = ["Banana", "yellow", "23", "Orange", "orange", "12", "Apple", "green", "10"];
Now I want to delete every second and third element. The result would look like this:
现在我想删除每第二个和第三个元素。结果如下所示:
["Banana", "Orange", "Apple"]
I tried to use a for-loop and splice:
我尝试使用 for 循环和拼接:
for (var i = 0; fruits.length; i = i+3) {
fruits.splice(i+1,0);
fruits.splice(i+2,0);
};
Of course this returns an empty array because the elements are removed while the loop is still executed.
当然,这将返回一个空数组,因为在仍然执行循环时删除了元素。
How can I do this correctly?
我怎样才能正确地做到这一点?
回答by McStretch
You could approach this from a different angle and push()the value you don't want deleted into another Array:
您可以从不同的角度处理这个问题,并将push()您不想删除到另一个数组中的值:
var firstFruits = []
for (var i = 0; i < fruits.length; i = i+3) {
firstFruits.push(fruits[i]);
};
This approach may not be as terse as using splice(), but I think you see gain in terms of readability.
这种方法可能不像使用 那样简洁splice(),但我认为您会看到可读性方面的收益。
回答by Robert
This works for me.
这对我有用。
var fruits = ["Banana", "yellow", "23", "Orange", "orange", "12", "Apple", "green", "10","Pear","something","else"];
for(var i = 0; i < fruits.length; i++) {
fruits.splice(i+1,2);
}
//fruits = Banana,Orange,Apple,Pear
Here's a demo that illustrates it a little better: http://jsfiddle.net/RaRR7/
这是一个演示,可以更好地说明它:http: //jsfiddle.net/RaRR7/
回答by Alexander Truslow
You could use filter:
您可以使用过滤器:
var filtered = [
"Banana",
"yellow",
"23",
"Orange",
"orange",
"12",
"Apple",
"green",
"10"
].filter(function(_, i) {
return i % 3 === 0;
})
Returns:
返回:
["Banana", "Orange", "Apple"]
回答by John
Try looping through the array in reverse order
尝试以相反的顺序循环遍历数组
回答by CodeMonkey1313
You'll want to move through the array backwards, then if i % 2 == 0 || i%3 == 0then splice the element from the array
您需要向后移动数组,然后i % 2 == 0 || i%3 == 0从数组中拼接元素
回答by Bhavya
Have you considered just copying the first, fourth, and seventh elements to a new array? It isn't very memory efficient but it'll still work fine.
您是否考虑过将第一个、第四个和第七个元素复制到新数组中?它的内存效率不是很高,但它仍然可以正常工作。

