vue.js map 函數(shù)是一個(gè)內(nèi)置的高階函數(shù),用于創(chuàng)建一個(gè)新數(shù)組,其中每個(gè)元素都是原始數(shù)組中的每個(gè)元素轉(zhuǎn)換后的結(jié)果。其語(yǔ)法為 map(callbackfn),其中 callbackfn 接收數(shù)組中的每個(gè)元素作為第一個(gè)參數(shù),可選地接收索引作為第二個(gè)參數(shù),并返回一個(gè)值。map 函數(shù)不會(huì)改變?cè)紨?shù)組。
Vue.js 中 map 函數(shù)
map 函數(shù)在 Vue.js 中是一個(gè)內(nèi)置的高階函數(shù),用于創(chuàng)建一個(gè)新數(shù)組,該數(shù)組中的每個(gè)元素都是根據(jù)原始數(shù)組中的每個(gè)元素轉(zhuǎn)換后的結(jié)果。
語(yǔ)法:
map(callbackFn)
登錄后復(fù)制
參數(shù):
callbackFn: 一個(gè)函數(shù),接收數(shù)組中的每個(gè)元素作為第一個(gè)參數(shù),可選地接收索引作為第二個(gè)參數(shù)。
返回值:
一個(gè)新數(shù)組,其中每個(gè)元素都是原始數(shù)組中相應(yīng)元素的轉(zhuǎn)換結(jié)果。
用法:
map 函數(shù)可以與數(shù)組方法一起使用,如下所示:
const numbers = [1, 2, 3, 4, 5]; // 將每個(gè)元素乘以 2 const doubledNumbers = numbers.map(number => number * 2); // 輸出:[2, 4, 6, 8, 10] console.log(doubledNumbers);
登錄后復(fù)制
實(shí)例:
map 函數(shù)可以用于:
轉(zhuǎn)換數(shù)組中的元素類(lèi)型
創(chuàng)建新的數(shù)組,只包含原始數(shù)組中滿(mǎn)足特定條件的元素
提取數(shù)組中嵌套對(duì)象或數(shù)組的特定屬性或值
示例用法:
// 創(chuàng)建一個(gè)新數(shù)組,只包含名字為 "John" 的用戶(hù) const users = [{ name: "John", age: 30 }, { name: "Jane", age: 25 }]; const johnUsers = users.map(user => user.name === "John" ? user : null); // 提取每個(gè)產(chǎn)品的價(jià)格 const products = [{ name: "Product 1", price: 10 }, { name: "Product 2", price: 15 }]; const prices = products.map(product => product.price);
登錄后復(fù)制
注意事項(xiàng):
map 函數(shù)不會(huì)改變?cè)紨?shù)組。
callbackFn 必須返回一個(gè)值。如果未返回任何值,則新數(shù)組中的相應(yīng)元素將為 undefined。