6 個JavaScript 中Map() 的用例

英文 | https://betterprogramming.pub/6-use-cases-for-map-in-javascript-a09f51ea2d2c
翻譯 | 楊小愛
map( ) 函數(shù)通過調(diào)用用戶提供的回調(diào)函數(shù)創(chuàng)建一個新數(shù)組。該函數(shù)訪問調(diào)用數(shù)組中的每個元素。您可以將 map( ) 方法視為經(jīng)過一個循環(huán)并在回調(diào)函數(shù)中編寫語句以構(gòu)造一個新數(shù)組。
參數(shù)是什么?
參數(shù)是回調(diào)函數(shù)和執(zhí)行回調(diào)函數(shù)時(shí)用作“this”的值。
回調(diào)函數(shù)
callBackFunction:對數(shù)組中的每個元素都調(diào)用該函數(shù),當(dāng)回調(diào)函數(shù)執(zhí)行完畢后,將返回值添加到將使用map()構(gòu)造的新數(shù)組中。
currentValue:它是數(shù)組的當(dāng)前元素,回調(diào)函數(shù)遍歷它。
index:回調(diào)函數(shù)正在處理的當(dāng)前元素的索引。
array:就是回調(diào)函數(shù)所經(jīng)過的數(shù)組。
This
thisArgument — 這是在執(zhí)行 callBackFunction 時(shí)用作 this 的值。
1、將數(shù)組元素加倍
您可以使用 map() 方法從另一個數(shù)組創(chuàng)建一個新數(shù)組。例如,您可以將整數(shù)數(shù)組的元素加倍并從初始數(shù)組構(gòu)造一個新數(shù)組。
let initialArray = [1,2,3,4,5]let doubles = initialArray.map( function(num) {return num*2})console.log(initialArray); // returns [1,2,3,4,5]console.log(doubles); // returns [2,4,6,8,10]
你也可以使用箭頭函數(shù)來做同樣的操作。
let initialArray = [1,2,3,4,5]let doubles = initialArray.map(x => x * 2);console.log(initialArray); // returns [1,2,3,4,5]console.log(doubles); // returns [2,4,6,8,10]
2、 重新格式化數(shù)組中的對象
您可以使用 map() 方法重新格式化對象數(shù)組。例如,您有一個包含人名和姓氏的對象數(shù)組。此外,您希望在 people 數(shù)組中創(chuàng)建一個包含人員全名的新數(shù)組。
var lineup = [{id: 1,firstName: "Magic",lastName: "Johnson"{id: 2,firstName: "Kobe",lastName: "Bryant"{id: 3,firstName: "Lebron",lastName: "James"{id: 4,firstName: "Kareem",lastName: "Abdul-Jabbar"{id: 5,firstName: "Shaquille",lastName: "O’Neal"}];
現(xiàn)在,您可以創(chuàng)建一個包含重新格式化對象的新數(shù)組。
let lineupSpeech = lineup.map( player => {let newObj = {};newObj["fullName"] = player.firstName + " " + player.lastName;return newObj;})console.log(lineup);/*[{ id: 1, firstName: 'Magic', lastName: 'Johnson' },{ id: 2, firstName: 'Kobe', lastName: 'Bryant' },{ id: 3, firstName: 'Lebron', lastName: 'James' },{ id: 4, firstName: 'Kareem', lastName: 'Abdul-Jabbar' },{ id: 5, firstName: 'Shaquille', lastName: 'O’Neal' }]*/console.log(lineupSpeech);/*[{ fullName: 'Magic Johnson' },{ fullName: 'Kobe Bryant' },{ fullName: 'Lebron James' },{ fullName: 'Kareem Abdul-Jabbar' },{ fullName: 'Shaquille O’Neal' }]*/
3、回調(diào)數(shù)組中的某些元素
您可以將指定的元素加倍,而不是將數(shù)組中的每個元素都加倍。例如,如果元素是奇數(shù),您可能希望將它們加倍。
const numArray = [1, 2, 3, 4];const sqrts = numArray.map( (num) => {return num % 2 === 1 ? Math.sqrt(num): num} );
4、將字符串轉(zhuǎn)換為數(shù)組
您可以使用 map() 方法將字符串轉(zhuǎn)換為數(shù)組。為此,您可以從 .call() 方法獲得幫助。
const language = "JavaScript"const map = Array.prototype.mapconst letters = map.call(language, eachLetter => {return `${eachLetter}`})console.log(letters) // ['J','a','v','a','S','c','r','i','p','t']
5、 遍歷一個 NodeList
您可以使用 map() 方法遍歷由 querySelectorAll() 收集的對象。這是可能的,因?yàn)?querySelectorAll() 返回一個 NodeList。
let NodeList = document.querySelectorAll(“p”);let values = Array.prototype.map.call(NodeList, function(obj) {return obj.value})
6、在 React.js 中渲染一個列表
您還可以在使用 React 庫時(shí)使用 map()。你可以在 React 中渲染一個列表。
import React from ‘react’;import ReactDOM from ‘react-dom’;const numbers = [1,2,3,4,5];const listItems = numbers.map( (number) =><li> {number} </li>);ReactDOM.render(<ul>{listItems}</ul>,document.getElementById('root'));
總結(jié)
JavaScript 中的內(nèi)置函數(shù)很有用。您可以使用它來構(gòu)造更復(fù)雜的函數(shù)。因此,了解這些函數(shù)對提高您對該編程語言的了解非常重要。
map() 也是一個有用的內(nèi)置 javascript 方法。您可以從另一個數(shù)組創(chuàng)建一個新數(shù)組,而無需使用 while 或 for 循環(huán)。
綜上所述,本文中map()方法的使用案例如下:
將數(shù)組的元素加倍
重新格式化數(shù)組中的對象
對數(shù)組中的某些元素應(yīng)用回調(diào)
將字符串轉(zhuǎn)換為數(shù)組
遍歷 NodeList
在 React 庫中渲染列表
最后,希望今天的內(nèi)容對您有所幫助,如果您覺得今天內(nèi)容有用的話,請記得分享給您身邊的朋友,也許可以幫助到他。
感謝您的閱讀,祝您編程愉快!
學(xué)習(xí)更多技能
請點(diǎn)擊下方公眾號
![]()

