TIM*_*MEX 27 javascript list node.js
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']
Run Code Online (Sandbox Code Playgroud)
我想使用forEach循环从列表中删除一个元素.
Gaj*_*jus 56
使用合适的工具来完成正确的工作.在这种情况下:
for (var i = 0; i < data.length; i++) {
if (data[i].value === 5) {
data.splice(i--, 1);
}
}
Run Code Online (Sandbox Code Playgroud)
或者@nnnnnn建议,向后循环:
for (var i = data.length-1; i >= 0; i--) {
if (data[i].value === 5) {
data.splice(i, 1);
}
}
Run Code Online (Sandbox Code Playgroud)
但是,您应该考虑使用Array.prototype.filter():
data = data.filter(function (e) {
return e.value !== 5;
});
Run Code Online (Sandbox Code Playgroud)
或者实用程序函数库,如lodash或underscore,它提供了从数组中删除元素的功能:
_.remove(data, function (e) {
return e.value === 5;
});
Run Code Online (Sandbox Code Playgroud)
后两者的好处是您的代码变得更具可读性.
Mrc*_*ief 30
您不应该修改正在循环的数组.但是你可以制作一个新的:
var newPeople = [];
people.forEach(function(p){
if(p.length <= 4){
newPeople.push(p);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
36852 次 |
| 最近记录: |