JavaScript Array map 方法

JavaScript About 993 words

映射为新字符串

const arr = ["Hello", "Hi", "How are you"];
const map1 = arr.map(item => item.toUpperCase());
console.log(map1)

输出

[
    "HELLO",
    "HI",
    "HOW ARE YOU"
]

() 圆括号式返回新对象

只是return方式的简写,用于直接返回一个对象,不能有其他业务逻辑。

const map2 = arr.map(item => ({
    length: item.length,
    content: item
}));
console.log(map2)

输出

[
    {
        "length": 5,
        "content": "Hello"
    },
    {
        "length": 2,
        "content": "Hi"
    },
    {
        "length": 11,
        "content": "How are you"
    }
]

return 方式返回新对象

return前可以有其他业务逻辑。

const arr2 = [
    {"id": 1, content: "Hello"},
    {"id": 2, content: "Hi"},
    {"id": 3, content: "How are you"},
];

const map3 = arr2.map(obj => {
    return {
        newId: obj.id,
        newContent: obj.content,
    }
});
console.log(map3)

输出

[
    {
        "newId": 1,
        "newContent": "Hello"
    },
    {
        "newId": 2,
        "newContent": "Hi"
    },
    {
        "newId": 3,
        "newContent": "How are you"
    }
]
Views: 8 · Posted: 2025-11-29

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓
Today In History
Browsing Refresh