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']
我想使用这个forEach循环从列表中删除一个元素。
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']
我想使用这个forEach循环从列表中删除一个元素。
使用合适的工具完成相应的工作。在这种情况下:
for (var i = 0; i < data.length; i++) {
if (data[i].value === 5) {
data.splice(i--, 1);
}
}
另外,如@nnnnnn所建议的,可以倒序循环:
for (var i = data.length-1; i >= 0; i--) {
if (data[i].value === 5) {
data.splice(i, 1);
}
}
不过,你应该考虑使用Array.prototype.filter()
方法:
data = data.filter(function (e) {
return e.value !== 5;
});
或者使用诸如lodash或underscore这样的实用函数库,它们提供了从数组中删除元素的函数:
_.remove(data, function (e) {
return e.value === 5;
});
后两者的好处是你的代码变得更易读。
.filter
看起来非常不错。 - Luca Steeb.filter()
不会修改数组,它会返回一个新的数组。我已经进行了编辑以反映这一点。你可能还想使用更短的 ES6 语法更新代码- data = data.filter(e => e.value !== 5);
- Kip您不应修改正在循环的数组。但是您可以生成一个新的数组:
var newPeople = [];
people.forEach(function(p){
if(p.length <= 4){
newPeople.push(p);
}
});
<=
?OP是小于4。@Mrchief - OP是“我想从列表中删除一个元素”,所以我认为意图是修改数组(大多数数组方法都是如此)。 - RobGfilter()
来实现这个功能:var people = ['alex','jason','matt'];
var shortPeople = people.filter(function(p){
return p.length <= 4);
});
console.log(people);
console.log(shortPeople);
const filterByLength = (arr, len) => arr.filter(s => s.length <= len);
const people = ["jon", "alex", "jason", "matt"];
console.log(filterByLength(people, 4)); // ["jon", "alex", "matt"]
从 ES5 开始,ForEach 可以与索引一起使用:
data.forEach(function (element, index) {
if (element % 2 == 0) {
data.splice(index, 1);
}
});
[1,28,35,444,555,666,333,424,313,303,484,464,121,12,14,88,96,108,1224,777]
,那么它将被转换为[1, 35, 555, 333, 313, 303, 464, 121, 14, 96, 1224, 777]
。 - Jessica Knight