App下載

在JavaScript中的Map() 方法怎么使用?相關(guān)案例內(nèi)容分享!

一顆跳動(dòng)的心 2021-09-09 17:05:14 瀏覽數(shù) (2294)
反饋

JavaScript 方法是可以對(duì)對(duì)象執(zhí)行的操作。那么本篇文章中我將介紹兩種 JavaScript 方法map()和filter(). 將簡(jiǎn)單而詳細(xì)地解釋。

地圖()

該map()方法用于對(duì)數(shù)組中的每個(gè)元素應(yīng)用一個(gè)函數(shù),然后返回一個(gè)新數(shù)組。我們來看看語法:

let newArray = array.map( (v, i, a) => {
    // return element to newArray
});
// newArray - the new array that is returned
// array - the array to run the map function on
// v - the current value being processed
// i - the current index of the value being processed
// a - the original array

map()方法可以被認(rèn)為是 for 循環(huán),即專門用于轉(zhuǎn)換值。讓我們看一下這個(gè)例子:

let nums = [11, 12, 13, 14];
let minus10 = [];
for(let i = 0; i < nums.length; i++) {
    minus10[i] = nums[i] - 10;
 }

代碼生成一個(gè)新數(shù)組,其中舊數(shù)組的每個(gè)值都減少 10。是的,它有效,但有一種更簡(jiǎn)單的方法可以實(shí)現(xiàn)相同的結(jié)果。

現(xiàn)在讓我們使用該map()方法重寫前面的函數(shù)。

let nums = [11, 12, 13, 14];
let minus10 = nums.map(value => value - 10);
  // minus10 = [1, 2, 3, 4]

使用箭頭函數(shù),我們有一個(gè)漂亮而干凈的函數(shù)來創(chuàng)建相同的數(shù)組。因?yàn)槲覀冎皇褂弥?,所以我們只將它傳遞給map()方法。

在此示例中,我們將同時(shí)使用 value 和 index 參數(shù):

let nums = [11, 12, 13, 14];
let newArray = nums.map( (v, i) => {
  return {
     value: v,
     index: i
   };
});

// newArr = [
// {value: 11, index: 0},
// {value: 12, index: 1},
// {value: 13, index: 2},
// {value: 14, index: 3}
//   ]

我想現(xiàn)在您會(huì)看到我們?cè)?code>map()方法中返回的任何內(nèi)容都用于創(chuàng)建新數(shù)組。您可以使用當(dāng)前值、當(dāng)前索引甚至整個(gè)數(shù)組來確定要返回的內(nèi)容。

你甚至可以在下面做這樣的蠢事(*laugh emoji*),然后只返回一個(gè)靜態(tài)字符串: 

let nums = [11, 12, 13, 14]; 
let cats = nums.map ( ( ) => 'cats');
 // cats = [`cat`, `cat`, `cat`, `cat` ]

到這里為止,所有的例子都轉(zhuǎn)換了舊數(shù)組中的所有值。讓我們看看一種轉(zhuǎn)換數(shù)組中某些值的方法。 

let nums = [11, 12, 13, 14]; 
ley newArr = nums.map(v => v % 2 === 0 ? v * 2 : v);
  // newArr = [11, 24, 13, 28];

首先,我們檢查值除以 2 的余數(shù)是否為零。如果余數(shù)為零,我們將返回 v * 2 或當(dāng)前值的兩倍。


0 人點(diǎn)贊