Skip to main content

forEach

概述

forEach() 方法对数组的每个元素执行一次给定的函数。

const array1 = ['a', 'b', 'c'];

array1.forEach(element => console.log(element));

// expected output: "a"
// expected output: "b"
// expected output: "c"

注意:forEach()会修改原来的数组,返回undefined

区别

  • forEach()会修改原来的数组,返回值为undefined。
  • map()方法会得到一个新的数组并返回。

函数式角度的理解

如果你习惯使用函数是编程,那么肯定喜欢使用map()。因为forEach()会改变原始的数组的值,而map()会返回一个全新的数组,原本的数组不受到影响。

链接

优秀文章: