浅谈 forEach()

用于遍历数组,无返回值

    let arr = [1, 2, 3, 4];
      arr.forEach(function(item,index,array){
          array[index]=item*2;
      })

      console.log(arr);//[2, 4, 6, 8]

可以看到,forEach()可以传入一个匿名函数作为参数,而该匿名函数有含有三个参数,其依次代表数组遍历时的当前元素item,数组遍历时的当前元素的索引index,以及正在遍历的数组array。有了这三个参数,可以方便我们做很多事情,比如说示例当中将每一项数组元素翻倍,这时需要用到第一个参数item。但是,仅仅只是将item乘以2可不行,我们还得将其赋值给原来的数组,这时我们就得用到后面两个参数index和array。

根据上述可知,array[index]是全等于item的。

arr.forEach(function(item,index,array){
    console.log(array[index] === item);   // true
});
发布了87 篇原创文章 · 获赞 3 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_38188762/article/details/105020429