ES6forEach( )

75 阅读1分钟

Array.prototype.forEach

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

语法

arr.forEach(callback(currentValue [, index [, array]])[, thisArg])

  • callback:为数组中每个元素执行的函数,该函数接收一至三个参数:
  • currentValue:数组中正在处理的当前元素。
  • index: 可选,数组中正在处理的当前元素的索引。
  • array: 可选, forEach() 方法正在操作的数组。

forEach() 对于空数组是不会执行回调函数的

arr.forEach((item,index)=>{})    

forEach三种形式    

1.箭头函数

forEach((element) => { /* …         */ })

forEach((element, index) => { /* … */ })

forEach((element, index, array) => { /* … */ })
  1. 回调函数
forEach(callbackFn)

forEach(callbackFn, thisArg)
  1. 内联回调函数
forEach(function(element) { /* … */ })

forEach(function(element, index) { /* … */ })

forEach(function(element, index, array){ /* … */ })

forEach(function(element, index, array) { /* … */ }, thisArg)