2026年10月5日 星期一

重新認識 Array.forEach()

 重新認識 Array.forEach()

前言

  最近發現 Array.forEach() 跟我之前認知的不太一樣,之前的認知它是簡化的 for 迴圈,但事實不然,在此把學習的過程作的紀錄。


內容

  範例如下

let ar = [ 5 , 6 , 7 , 8 , 9 ];
ar.forEach( (ele) =>{
  console.log( `ele:${ ele }`);
});
//ele:5
//ele:6
//ele:7
//ele:8
//ele:9
//
ar.forEach( (ele , index , array ) =>{
  console.log( `index:${index} ele:${ele}`);
});
//index:0 ele:5
//index:1 ele:6
//index:2 ele:7
//index:3 ele:8
//index:4 ele:9


Array.forEach() 不只是簡化的 for 迴圈,之前的認知如範例開頭用法,可以瀏覽陣列每個元素,但如果要像 for 迴圈一樣知道目前是第幾個元素是要加變數計數的,但事實不然,可以想像之前的這個用法是簡化的用法,查閱 [ developer.mozilla.org ] Array.prototype.forEach() 可以發現 callbackfn 其實有三個引數,第一個就是元素,第二個則是第幾個元素,第三個則是陣列自己,所以範例最後使用三個引數的方式列印出元素與第幾個元素。


參考資料

[ developer.mozilla.org ] Array.prototype.forEach()