forEach 范围问题

forEach 范围问题

先来思考下面两段代码

let arr = [1,2,3,4];

arr.forEach((item) => {
    if(item==2){
        arr.push(100);
    }
    console.log(item); 
});
console.log(arr);

// 结果
// > 1
// > 2
// > 3
// > 4

// > [1,2,3,4,100]

let arr = new Set([1,2,3,4]);

arr.forEach((item) => {
    if(item==2){
       arr.add(100)
    }
    console.log(item); 
});
console.log(Array.from(arr));

// 结果
// > 1
// > 2
// > 3
// > 4
// > 100

// > [1,2,3,4,100]

我们发现,arraysetforEach中打印的结果是不同的,array并没有打印出我新添加的值,而set则是可以的,这是为什么?

假如我在forEach set 的时候没有条件,使用add的话。

let arr = new Set([1,2,3,4]);

arr.forEach((item) => {
    // set的值添加重复的无意义 则改为每次添加的都 item+1
    arr.add(item+1)
});
console.log(Array.from(arr));

// 结果
// [angeError: Value undefined out of range for undefined options property undefined
//    1,  2,  3,   4,  5,  6,  7,  8,  9, 10, 11, 12,
//   13, 14, 15,  16, 17, 18, 19, 20, 21, 22, 23, 24,
//   25, 26, 27,  28, 29, 30, 31, 32, 33, 34, 35, 36,
//   37, 38, 39,  40, 41, 42, 43, 44, 45, 46, 47, 48,
//   49, 50, 51,  52, 53, 54, 55, 56, 57, 58, 59, 60,
//   61, 62, 63,  64, 65, 66, 67, 68, 69, 70, 71, 72,
//   73, 74, 75,  76, 77, 78, 79, 80, 81, 82, 83, 84,
//   85, 86, 87,  88, 89, 90, 91, 92, 93, 94, 95, 96,
//   97, 98, 99, 100,
//   ... 16777116 more items
// ]

查找资料了解其中缘由

  • array.forEach
    • forEach() 遍历的范围在第一次调用 callback 前就会确定。
    • 调用 forEach 后添加到数组中的项不会被 callback 访问到。
    • 如果已经存在的值被改变,则传递给 callback 的值是 forEach() 遍历到他们那一刻的值。
    • 已删除的项不会被遍历到。如果已访问的元素在迭代时被删除了(例如使用 shift()),之后的元素将被跳过

总结来说:当我们使用forEach 开始,循环的次数定了,新添加的不会影响循环次数,删除元素则会影响循环次数,并且修改元素要在元素回调前修改方可生效。例如在forEach shift 回调里的打印和回调外的打印环境是不一致的。

let arr = [1, 2, 3, 4];

arr.forEach((item) => {
    if (item == 1) {
        arr.shift();
        arr.push(1000);
    }
    console.log(item);
});
console.log(arr);

// 结果
// > 1
// > 3
// > 4

// > [2,3,4]

  • set.forEach

这一点 set.forEach 则符合我们想的那种思维感觉,只要添加了就接着循环回调,所以在无任何条件下就会出现无限循环。

拓展

let arr = [0,1,2,3,4,5]; 数组,删除索引为 0 2 3,使用 for 循环删除,如何保证不删错?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值