简体   繁体   中英

Why should we decrement an i variable and use break in a function?

What is the purpose of decrementing the "i" variable and using "break" in this function?

function filteredArray(arr, elem){
  let newArr = [...arr];
  for(let i = 0; i < newArr.length; i++){
    for(let j = 0; j < newArr[i].length; j++){
      if(newArr[i][j] === elem){
        newArr.splice(i, 1);
        i--;
        break;
      }
    }
  }
  return newArr;
}

console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));

This is because by using newArr.splice(i, 1); you are removing the current index item from the array, so since all indexes will be moved by -1 for all elements following i at each splice, you then have to reduce i by 1, so you dont skip elements

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM