亚洲日本永久一区二区_国产精品k频道网址导航_首页aⅴ色老汉中文字幕_免费深夜全片观看_9久久9毛片又大又硬又粗_国产精品成亚洲电影_日韩不用播放器的av_欧美特色特黄视频

JavaScript 數組方法 .map() 的 5 個使用場景

JavaScript 數組方法 .map() 的 5 個使用場景

.map() 函數是 JavaScript 數組結構中很實用的一個方法之一,更多可以參閱《JavaScript 數據結構之 Array》。本文主要介紹一下.map() 函數常用的場景,其通過調用回調函數創建一個新數組。該函數訪問調用數組中的每個元素。可以將 map() 方法視為經過一個循環并在回調函數中編寫語句(格式化、數據處理)以構造一個新數組。

語法

const newArray = array.map(function callback(currentValue[, index[, array]]) {
 // 為新數組返回新的元素
}[, thisArg])

.map() 函數用于遍歷數組元素。它接受一個回調函數作為參數,根據回調函數返回一個新數組和新元素。

.map() 方法是一個用來創建新數組、修改其內容并保持原始數組不變的通用方法。當出現需要修改現有數組的內容并將結果存儲為新變量的時候就可以用。

參數

  • callback(必須):生成新數組元素的函數,接收三個參數:

    • currentValuecallback 數組中正在處理的當前元素。
    • index:可選,callback 數組中正在處理的當前元素的索引。
    • array:可選,map 方法調用的數組。
  • thisArg:可選,執行 callback 函數時值被用作 this

返回值

一個由原數組每個元素執行回調函數的結果組成的新數組。

當需要更新數組中的所有項并將其存儲到一個新數組中時,.map() 方法就可以派上用場了。

1. 元素翻倍

可以使用 .map() 方法從另一個數組創建一個新數組。例如,可以將一個整數數組的每個元素翻倍構造一個新數組。

const arrayNumbers = [1, 2, 3, 4, 5];

const doubles = (array) => array.map((num) => num * 2);

console.log(arrayNumbers); // [ 1, 2, 3, 4, 5 ]
console.log(doubles(arrayNumbers)); // [ 2, 4, 6, 8, 10 ]

2. 元素格式化

可以使用 .map() 方法格式化對象數組。例如,有一個對象數組,對象屬性包含 usernameaddressage 等,現在需要一個由 username 組成的數組,這樣的場景就非常適合 .map() 方法。

const arrayUsers = [
    {
        id: 1,
        username: "Magic",
        address: "Johnson",
    },
    {
        id: 2,
        username: "Kobe",
        address: "Bryant",
    },
    {
        id: 3,
        username: "Lebron",
        address: "James",
    },
    {
        id: 4,
        username: "Kareem",
        address: "Abdul-Jabbar",
    },
    {
        id: 5,
        username: "Shaquille",
        address: "O’Neal",
    },
];
const newUsers = arrayUsers.map((item) => item.username);
console.log(arrayUsers);
// [
//     { id: 1, username: 'Magic', address: 'Johnson' },
//     { id: 2, username: 'Kobe', address: 'Bryant' },
//     { id: 3, username: 'Lebron', address: 'James' },
//     { id: 4, username: 'Kareem', address: 'Abdul-Jabbar' },
//     { id: 5, username: 'Shaquille', address: 'O’Neal' }
//   ]
console.log(newUsers); // [ 'Magic', 'Kobe', 'Lebron', 'Kareem', 'Shaquille' ]

從上面的接口可以看到,.map() 不會對原數組進行改造。

3. 回調數組中的某些元素

可以將指定的元素翻倍,而不是將數組中的每個元素都翻倍。例如,只對數組中的奇數元素進行翻倍。

const arrayNumbers = [1, 2, 3, 4];
const doubles = (nums) => nums.map((num) => (num % 2 === 1 ? num * 2 : num));
console.log(arrayNumbers); // [ 1, 2, 3, 4 ]
console.log(doubles(arrayNumbers)); // [ 2, 2, 6, 4 ]

4. 將字符串轉換為數組

可以使用 .map() 方法將字符串轉換為數組。

const language = "China";
const map = Array.prototype.map;
const letters = map.call(language, (eachLetter) => `${eachLetter}`);

console.log(letters); // [ 'C', 'h', 'i', 'n', 'a' ]

5. 在 React.js 中渲染列表

還可以在 React 中使用 .map() 來渲染一個列表。

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"));