Javascript 如何使用 forEach 删除列表中的元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6950236/
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
How do I remove an element in a list, using forEach?
提问by TIMEX
var people = ['alex','jason','matt'];
people.forEach(function(p){
if(p.length > 4){
//REMOVE THIS PERSON or pop it out of the list or whatever
}
});
console.log(people) //should return ['alex','matt']
I want to remove an element out of the list, using this forEach loop.
我想使用这个 forEach 循环从列表中删除一个元素。
回答by Gajus
Use the right tools for the right job. In this case:
为正确的工作使用正确的工具。在这种情况下:
for (var i = 0; i < data.length; i++) {
if (data[i].value === 5) {
data.splice(i--, 1);
}
}
or as @nnnnnn has suggested, loop backwards:
或者正如@nnnnnn 所建议的那样,向后循环:
for (var i = data.length-1; i >= 0; i--) {
if (data[i].value === 5) {
data.splice(i, 1);
}
}
However, you should consider using Array.prototype.filter()
:
但是,您应该考虑使用Array.prototype.filter()
:
data = data.filter(function (e) {
return e.value !== 5;
});
or a utility function library such as lodashor underscore, which provide a function for removing elements from an array:
或一个实用函数库,例如lodash或underscore,它们提供了从数组中删除元素的函数:
_.remove(data, function (e) {
return e.value === 5;
});
The benefit of the latter two is that your code becomes more readable.
后两者的好处是您的代码变得更具可读性。
回答by Mrchief
You shouldn'tmodify the array you're looping on. You can produce a new one, though:
你不应该修改你正在循环的数组。不过,您可以制作一个新的:
var newPeople = [];
people.forEach(function(p){
if(p.length <= 4){
newPeople.push(p);
}
});
回答by adripanico
ForEach, since ES5 can be used together with an index:
ForEach,由于 ES5 可以与索引一起使用:
data.forEach(function (element, index) {
if (element % 2 == 0) {
data.splice(index, 1);
}
});
回答by Code-Apprentice
You can do this very easily with filter()
:
你可以很容易地做到这一点filter()
:
var people = ['alex','jason','matt'];
var shortPeople = people.filter(function(p){
return p.length <= 4);
});
console.log(people);
console.log(shortPeople);