JS 提供許多方法來處理陣列,map()是常用的幾種方法之一,以下整理幾種常用的情境及使用方法,方便自己記憶與複習。
基本語法
- map() 方法對陣列中每個元素進行處理,並回傳一個長度相同的新陣列,且不會改變原始陣列
使用情境一:資料轉換
let new_array = arr.map(function callback( currentValue[, index[, array]]) {
// return element for new_array
}[, thisArg])
只提取物建中某個屬性組成新陣列
const users = [
{id:1,name:'Mary',email:'mary@gmail.com'},
{id:2,name:'John',email:'john@gmail.com'}
];
const userName = users.map(user => users.name)
使用情境二 :數值運算與修正
對陣列中的數值進行統一的數學運算,並回傳一個新陣列。例如打折、單位換算
const prices = [100,200,300]
// 打 8 折
const discountPrice = prices.map(price=>price * 0.8)
情境三:替物件新增或修改屬性
在不破壞原始資料的狀況下,為每個物件增加新屬性
const students = [
{name:'John',scores:55},
{name:'Mary',scores:70}
];
const gradedStudents = students.map(student=>{
...student,
passed:student.scores >= 60
})
情境4:搭配其他陣列方法
map() 常常跟 filter() 串聯使用,先用 filter() 篩選資料再用 map()轉換資料
const students = [
{name:'John',scores:55},
{name:'Mary',scores:70}
];
const result = students.filter(s=> student.scores >= 60).map(s=> s.name)
使用小技巧與注意事項特性
| 特性 | 說明 |
|---|---|
| 回傳新陣列 | map() 不會改變原陣列 (Immutability),這對除錯很有幫助。 |
| 長度一致 | 回傳的新陣列長度一定會等於原陣列長度。 |
| 避免副作用 | 盡量不要在 map() 裡面執行 console.log 或修改外部變數,那是 forEach 的工作。 |
| 一定要有 return | 如果忘記寫 return,新陣列的元素會變成 undefined。 |
