forEach是如何执行的

  1. callback 在forEach执行之前,他的执行范围、内容已经确定。
  2. callback 执行的值就是索引所对应的值
  3. 如果传入的值不存在, 循环便会停止

需要终止循环推荐使用:

简单循环 for…of 循环

Array.prototype.every()

Array.prototype.some()

Array.prototype.find()

Array.prototype.findIndex()

callback 执行的值就是索引所对应的值

将会一直输出 1 ,因为打印1之后一直往数组前追加了4,索引变化后 1数字 一直被追加的数字往后挤 。

  1. const array = [1,2,3]
  2. array.forEach(item => {
  3. console.log(item) // 将会一直输出 1
  4. array.unshift(4) // 数组前面追加值
  5. })
  6. console.log(array) // [4, 4, 4, 1, 2, 3]

使用return 和 break 为什么不能终止

将forEach转换成普通for循环如下

  1. const array = [1, 2, 3];
  2. for (let i = 0; i < array.length; i++) {
  3. (function(item) {
  4. console.log(item);
  5. if (item === 2) return false;
  6. })(array[i])
  7. }

停止forEach

  1. const array = [1, 2, 3]
  2. array.forEach((item, i) => {
  3. console.log(item)
  4. if (item === 2) { // 当2的时候就会停止
  5. array.splice(i, array.length - 1) // 删除后面值不存在就会停止,但是会破坏数组
  6. }
  7. })
  8. console.log(array) // [1]
  • 不破坏数组,将删除的数组合并
    1. let array=[1, 2, 3, 4, 5]
    2. array.forEach(item=>{
    3. console.log(item)
    4. if (item == 2) {
    5. array = array.splice(0);
    6. }
    7. })
    8. console.log(item);