一、概念
map()
方法定義在JavaScript的Array
中颁督,它返回一個(gè)新的數(shù)組瑰剃,數(shù)組中的元素為原始數(shù)組調(diào)用函數(shù)處理后的值。
注意:
-
map()
不會(huì)對(duì)空數(shù)組進(jìn)行檢測 -
map()
不會(huì)改變原始數(shù)組
二嗦锐、語法
array.map(function(currentValue, index, arr), thisIndex)
參數(shù)說明:
-
function(currentValue, index, arr)
:必須。為一個(gè)函數(shù)沪曙,數(shù)組中的每個(gè)元素都會(huì)執(zhí)行這個(gè)函數(shù)奕污。其中函數(shù)參數(shù):
currentValue
:必須。當(dāng)前元素的的值液走。index
:可選碳默。當(dāng)前元素的索引。arr
:可選缘眶。當(dāng)前元素屬于的數(shù)組對(duì)象嘱根。
-
thisValue
:可選。對(duì)象作為該執(zhí)行回調(diào)時(shí)使用巷懈,傳遞給函數(shù)该抒,用作"this
"的值。
三顶燕、實(shí)例
返回由原數(shù)組中每個(gè)元素的平方組成的新數(shù)組:
let array = [1, 2, 3, 4, 5];
let newArray = array.map((item) => {
return item * item;
})
console.log(newArray) // [1, 4, 9, 16, 25]