通過(guò) 6 個(gè)簡(jiǎn)單的實(shí)例復(fù)習(xí)下JS 的 Map() 函數(shù)

英文 | https://betterprogramming.pub/6-use-cases-for-map-in-javascript-a09f51ea2d2c
翻譯 | 楊小愛(ài)
map( ) 函數(shù)通過(guò)調(diào)用用戶提供的回調(diào)函數(shù)創(chuàng)建一個(gè)新數(shù)組。該函數(shù)訪問(wèn)調(diào)用數(shù)組中的每個(gè)元素。您可以將 map( ) 方法視為經(jīng)過(guò)一個(gè)循環(huán)并在回調(diào)函數(shù)中編寫(xiě)語(yǔ)句以構(gòu)造一個(gè)新數(shù)組。
參數(shù)是什么?
參數(shù)是回調(diào)函數(shù)和執(zhí)行回調(diào)函數(shù)時(shí)用作“this”的值。
回調(diào)函數(shù)
callBackFunction:對(duì)數(shù)組中的每個(gè)元素都調(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)過(guò)的數(shù)組。
This
thisArgument — 這是在執(zhí)行 callBackFunction 時(shí)用作 this 的值。
1、將數(shù)組元素加倍
您可以使用 map() 方法從另一個(gè)數(shù)組創(chuàng)建一個(gè)新數(shù)組。例如,您可以將整數(shù)數(shù)組的元素加倍并從初始數(shù)組構(gòu)造一個(gè)新數(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ù)來(lái)做同樣的操作。
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ù)組中的對(duì)象
您可以使用 map() 方法重新格式化對(duì)象數(shù)組。例如,您有一個(gè)包含人名和姓氏的對(duì)象數(shù)組。此外,您希望在 people 數(shù)組中創(chuàng)建一個(gè)包含人員全名的新數(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)建一個(gè)包含重新格式化對(duì)象的新數(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ù)組中的每個(gè)元素都加倍。例如,如果元素是奇數(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、 遍歷一個(gè) NodeList
您可以使用 map() 方法遍歷由 querySelectorAll() 收集的對(duì)象。這是可能的,因?yàn)?querySelectorAll() 返回一個(gè) NodeList。
let NodeList = document.querySelectorAll(“p”);let values = Array.prototype.map.call(NodeList, function(obj) {return obj.value})
6、在 React.js 中渲染一個(gè)列表
您還可以在使用 React 庫(kù)時(shí)使用 map()。你可以在 React 中渲染一個(gè)列表。
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ù)很有用。您可以使用它來(lái)構(gòu)造更復(fù)雜的函數(shù)。因此,了解這些函數(shù)對(duì)提高您對(duì)該編程語(yǔ)言的了解非常重要。
map() 也是一個(gè)有用的內(nèi)置 javascript 方法。您可以從另一個(gè)數(shù)組創(chuàng)建一個(gè)新數(shù)組,而無(wú)需使用 while 或 for 循環(huán)。
綜上所述,本文中map()方法的使用案例如下:
將數(shù)組的元素加倍
重新格式化數(shù)組中的對(duì)象
對(duì)數(shù)組中的某些元素應(yīng)用回調(diào)
將字符串轉(zhuǎn)換為數(shù)組
遍歷 NodeList
在 React 庫(kù)中渲染列表
最后,希望今天的內(nèi)容對(duì)您有所幫助,如果您覺(jué)得今天內(nèi)容有用的話,請(qǐng)記得分享給您身邊的朋友,也許可以幫助到他。
感謝您的閱讀,祝您編程愉快!
學(xué)習(xí)更多技能
請(qǐng)點(diǎn)擊下方公眾號(hào)
![]()
