如何使用forEach删除列表中的元素? [英] How do I remove an element in a list, using forEach?

查看:106
本文介绍了如何使用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循环从列表中删除一个元素。

I want to remove an element out of the list, using this forEach loop.

推荐答案

不应该修改你正在循环的数组。但是你可以产生一个新的:

You shouldn't modify 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);
    }
});

这篇关于如何使用forEach删除列表中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆