How to remove element from array in forEach loop?

前端 未结 7 490
耶瑟儿~
耶瑟儿~ 2020-11-28 03:37

I am trying to remove an element in an array in a forEach loop, but am having trouble with the standard solutions I\'ve seen.

This is what I\'m current

相关标签:
7条回答
  • 2020-11-28 04:06

    Although Xotic750's answer provides several good points and possible solutions, sometimes simple is better.

    You know the array being iterated on is being mutated in the iteration itself (i.e. removing an item => index changes), thus the simplest logic is to go backwards in an old fashioned for (à la C language):

    let arr = ['a', 'a', 'b', 'c', 'b', 'a', 'a'];
    
    for (let i = arr.length - 1; i >= 0; i--) {
      if (arr[i] === 'a') {
        arr.splice(i, 1);
      }
    }
    
    document.body.append(arr.join());

    If you really think about it, a forEach is just syntactic sugar for a for loop... So if it's not helping you, just please stop breaking your head against it.

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