[ JS筆記 ] forEach()、map()差別


Posted by Akira on 2022-01-06

定義

先來看看MDN中定義的map()和forEach()

  • mapmap() 方法會建立一個新的陣列,其內容為原陣列的每一個元素經由回呼函式運算後所回傳的結果之集合。
  • forEachforEach() 方法會將陣列內的每個元素,皆傳入並執行給定的函式一次。

嗯...看起來兩個功能差不多,都是遍歷陣列中的元素。主要差在map會回傳新的陣列,而forEach則會修改原陣列。

使用

我們實際使用看看差別在哪。
先給一個原陣列。

let array = ["a", "b", "c",]

將陣列中的元素都加上"+d",試用兩種方式:

map()

  • 原陣列不改變,會回傳新的陣列。
  • 每一次執行匿名函式都支援三個引數,陣列當前項元素item,當前項索引index,原始陣列input。
  • 匿名函式中的this都是指window,可以在匿名函式後指定this。
let array = ['a', 'b', 'c',]

let array2 = array.map(function(item, index, array){
    return item + '+d'
})

let array3 = array.map(function(item, index, array){
    console.log('this', this[index])
    return item + '+d'
},array)

console.log(array)
console.log(array2)
console.log(array3)

// this a
// this b
// this c
// [ 'a', 'b', 'c' ] 原陣列不改變
// [ 'a+d', 'b+d', 'c+d' ] 
// [ 'a+d', 'b+d', 'c+d' ]

用不到index、input的情況之下,可以不寫,並簡化成箭頭函示。

let array = ['a', 'b', 'c',]

let array2 = array.map(item => item + '+d')

console.log(array) // [ 'a', 'b', 'c' ]
console.log(array2) // [ 'a+d', 'b+d', 'c+d' ]

是不是看起來清爽多了!

總結:map()適合用在需要改動資料的時候。將原始的變數運算後重新組合一個新的陣列。

forEach()

  • 原陣列改變,沒有回傳值(沒有return)。
  • 每一次執行匿名函式都支援三個引數,陣列當前項元素item,當前項索引index,原始陣列input。
  • 匿名函式中的this都是指window,可以在匿名函式後指定this。
let array = ['a', 'b', 'c',]

let array2 = array.forEach(function(item, index, array){
    array[index] = item + '+d'
})

console.log(array2) // undefined 不會額外回傳值
let array = ['a', 'b', 'c',]

array.forEach(function(item, index, array){
    array[index] = item + '+d'
})

console.log(array) // [ 'a+d', 'b+d', 'c+d' ] 原陣列改變了

forEach()同樣也可以指定this。

let array = ['a', 'b', 'c',]

array.forEach(function(item, index, array){
    console.log('this', this[index])
    array[index] = item + '+d'
},array)

console.log(array)

// this a
// this b
// this c
// [ 'a+d', 'b+d', 'c+d' ]

總結:forEach適合沒有改動資料,只是想用資料做點事情的情況。例如:列印出來(console.log())或是存到資料庫。

相同與相異之處

參考資料:https://wcc723.github.io/javascript/2017/06/29/es6-native-array/










Related Posts

【筆記】Git 入門筆記——使用 GitHub

【筆記】Git 入門筆記——使用 GitHub

【Day02】 計算屬性, 監聽器 & 事件處理

【Day02】 計算屬性, 監聽器 & 事件處理

[Power BI] 讀書會 #6 Power BI建立資料連結

[Power BI] 讀書會 #6 Power BI建立資料連結


Comments