How do I remove an element in a list, using forEach?

前端 未结 4 663
抹茶落季
抹茶落季 2020-12-03 09:38
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
          


        
相关标签:
4条回答
  • 2020-12-03 10:14

    ForEach, since ES5 can be used together with an index:

    data.forEach(function (element, index) {
      if (element % 2 == 0) {
        data.splice(index, 1);
      }
    });
    
    0 讨论(0)
  • 2020-12-03 10:22

    You can do this very easily with filter():

    var people = ['alex','jason','matt'];
    
    var shortPeople = people.filter(function(p){
        return p.length <= 4);
    });
    
    console.log(people);
    console.log(shortPeople);
    
    0 讨论(0)
  • 2020-12-03 10:28

    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);
        }
    });
    

    Why you shouldn't modify array you're looping.

    0 讨论(0)
  • 2020-12-03 10:34

    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:

    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():

    data = data.filter(function (e) {
        return e.value !== 5;
    });
    

    or a utility function library such as lodash or underscore, which provide a function for removing elements from an array:

    _.remove(data, function (e) {
        return e.value === 5;
    });
    

    The benefit of the latter two is that your code becomes more readable.

    0 讨论(0)
提交回复
热议问题