JavaScript 五四三 Ep.04 Array.prototype.map()


Posted by ABow_Chen on 2022-09-22

一、map() 簡介

  1. 對陣列使用 map() 方法,會建立一個新的陣列。
  2. 新的陣列的內容,是經由將原陣列中的元素代入到函式中,經過函式運算後所得。
  3. 不會改變原陣列。
  4. 若使用 map() 的原陣列是一個稀疏陣列(sparse array,即某些索引位置留空),則回傳之新陣列也會在同樣的索引位置留空。

     const array1 = [1, 4, , 9, , 16];
     const map1 = array1.map(function(x){
         return x*2
     });
    
     console.log(map1); // [2,8,,18,,32]
    

二、map() 語法

var new_array = arr.map(function callback( currentValue[, index[, array]]) {
    // return element for new_array
}[, thisArg])
  • callback: 這個 callback 函式,會把陣列中的每一個元素當成參數,帶入 callback 函式中,經過函式運算後加至新陣列,可傳入三個參數:
    • currentValue: 目前被處理中的原陣列裡的元素。
    • index(選擇性): 上述元素的索引值。
    • array(選擇性): 使用 map() 的陣列本身,即上述語法中的 arr
  • thisArg:執行 callback 函式的 this 值(即參考的物件)。

語法的執行範例如下:

var numbers = [2, 4, 6, 8, 10];
var newNumbers = numbers.map(function(num){
  return num/2;
});

console.log(newNumbers);// [1,2,3,4,5]

ES6 的寫法:

const numbers = [2, 4, 6, 8, 10];
const newNumbers = numbers.map(num => num/2);

console.log(newNumbers);// [1,2,3,4,5]

三、map() 常見用法

  1. 將原陣列重新運算後產生新陣列

     const numArray = [1, 3, 5, 7, 9];
     const newNumArray = numArray.map(num => num*3);
     console.log(newNumArray);// [3,9,15,21,27]
    
  2. 稍微複雜的資料處理

     const toy = [{name:"robot", price: 3000},{name:"puzzle", price:850}]
     const toyName = toy.map(x => x.name);
     console.log(toyName); // ["robot","puzzle"
    
     // 將玩具價格打 8 折
     const discounts = toy.map(y => y.price*0.8);
     console.log(discounts); // [2400,680]
    
  3. 將兩個陣列組合成一組資料

     const comics = ["黃金神威", "JoJo的奇妙冒險", "國王排名"]
     const prices = [99, 85, 150];
     const comicDatas = comics.map((comic,index) =>({comicName:comic,comicPrice:prices[index]}));
     console.log(comicDatas);
     //[
     // {comicName:"黃金神威", comicPrice: 99},
     // {comicName:"JoJo的奇妙冒險", comicPrice: 85},
     // {comicName:"國王排名", comicPrice: 150}
     //]
    

參考資料:

https://ithelp.ithome.com.tw/articles/10228634

https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/map


#javascript #map







Related Posts

Day03 : 字典、集合

Day03 : 字典、集合

讀書筆記-版本控制使用Git: 合併

讀書筆記-版本控制使用Git: 合併

關於 React 小書:前端應用狀態管理—狀態提升

關於 React 小書:前端應用狀態管理—狀態提升


Comments