splice not removing elements when called in a loop

前端 未结 1 640
无人共我
无人共我 2020-12-22 06:45

I am writing a code which takes an input string and an array of markers and removes everything from the markers to the end of the on which it is found. I have a function whi

相关标签:
1条回答
  • 2020-12-22 07:20

    You need to work backwards through the positions array, because when you splice out some elements of arr, the indexes of everything after those elements change.

    function solution(input, markers){
      var positions = identify(input, markers);
      var arr = input.split('');
    
      for(var i = positions.length-2; i >= 0; i-=2){
        arr.splice(positions[i], positions[i+1] - positions[i]);
        console.log(positions[i+1]);
      }
      return arr.join('');
    }
    
    0 讨论(0)
提交回复
热议问题