简体   繁体   English

FreeCodeCamp:使用For循环遍历数组的所有项目

[英]FreeCodeCamp: Iterating Through All an Array's Items Using For Loops

I've got this working block of code from the freecodecamp hint 我从freecodecamp提示中获得了这个工作代码块

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

I understand most part of it but not i--; break; 我了解大部分内容,但我不明白i--; break; i--; break; I really need an explanation as to why i--; break; 我真的需要一个解释,为什么i--; break; i--; break; was used. 被使用了。

https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-all-an-arrays-items-using-for-loops/ https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-all-an-arrays-items-using-for-loops/

This is a common question when a developer says, this code is skipping indexes. 当开发人员说此代码正在跳过索引时,这是一个常见问题。

You are altering the original array and removing the index. 您正在更改原始数组并删除索引。 So think about it like a stack of blocks. 因此,像一堆积木一样思考它。 You remove one, all of the ones above it drop down one. 删除一个,上面的所有下拉一个。

So you are removing an item with splice, so you need to reduce the index by one so you do not skip over the item that fills in the gap. 因此,您要删除带有拼接的项目,因此需要将索引减少一个,这样就不会跳过填补空白的项目。

A [B] C D E <-- before 
   ^
A [C] D E   <-- after

This is why people normally loop from the end to the start to avoid this. 这就是为什么人们通常从头到尾循环来避免这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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