這篇文章主要介紹了如何在JavaScript中使用Map()方法,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
該map()方法用于對數組中的每個元素應用一個函數,然后返回一個新數組。我們來看看語法:
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()
方法可以被認為是 for 循環,即專門用于轉換值。讓我們看一下這個例子:
let nums = [11, 12, 13, 14];
let minus10 = [];
for(let i = 0; i < nums.length; i++) {
minus10[i] = nums[i] - 10;
}
代碼生成一個新數組,其中舊數組的每個值都減少 10。是的,它有效,但有一種更簡單的方法可以實現相同的結果。
現在讓我們使用該map()方法重寫前面的函數。
let nums = [11, 12, 13, 14];
let minus10 = nums.map(value => value - 10);
// minus10 = [1, 2, 3, 4]
使用箭頭函數,我們有一個漂亮而干凈的函數來創建相同的數組。因為我們只使用值,所以我們只將它傳遞給map()方法。
在此示例中,我們將同時使用 value 和 index 參數:
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}
// ]
我想現在您會看到我們在map()
方法中返回的任何內容都用于創建新數組。您可以使用當前值、當前索引甚至整個數組來確定要返回的內容。
你甚至可以在下面做這樣的蠢事(*laugh emoji*),然后只返回一個靜態字符串:
let nums = [11, 12, 13, 14];
let cats = nums.map ( ( ) => 'cats');
// cats = [`cat`, `cat`, `cat`, `cat` ]
到這里為止,所有的例子都轉換了舊數組中的所有值。讓我們看看一種轉換數組中某些值的方法。
let nums = [11, 12, 13, 14];
ley newArr = nums.map(v => v % 2 === 0 ? v * 2 : v);
// newArr = [11, 24, 13, 28];
首先,我們檢查值除以 2 的余數是否為零。如果余數為零,我們將返回 v * 2 或當前值的兩倍。
感謝你能夠認真閱讀完這篇文章,希望小編分享的“如何在JavaScript中使用Map()方法”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。