一、概念
map() 函式本身不改變原陣列,而是處理完資料后重新回傳一個新陣列,新陣列中的元素是原陣列中的每個元素執行回呼函式后的回傳值,在該回呼函式中可根據需要處理資料并回傳,
注意:當需要同時修改原陣列時,可以在 callback 執行程序中給原陣列重新賦值,
二、語法
arr.map( callback( currentElement, currentIndex, originalArray), thisObj )
說明:
callback 是傳入 map() 的回呼函式,是必傳引數,
thisObj 傳入時會被用作回呼函式的 this 值,是可選引數
currentElement 指 callback 當前元素,必傳引數,
currentIndex 指 callback 當前元素的索引,可選引數,
originalArray 指被處理的陣列,即原陣列,可選引數,
三、示例
1、回傳新陣列:由原陣列中每個元素的10倍數值組成的,
let originArray = [ 2, 4, 6, 8 ]
let newArray = originArray.map(function(currentElement){
return currentElement * 10
})
console.log(newArray) // 輸出結果為:[20, 40, 60, 80]
簡寫方式:
let newArray = originArray.map( item => (item * 10) )
console.log(newArray) // 輸出結果為:[20, 40, 60, 80]
2、修改原陣列:將原陣列中每個元素的數字擴大20倍,
let originArray = [ 2, 4, 6, 8 ]
originArray.map((cur,index) => ( originArray[index] = cur * 20 ) )
console.log(originArray ) // 輸出結果為:[40, 80, 120, 160]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/390376.html
標籤:其他
上一篇:day12 - JavaScript的三大組成部分及方法、移動端適配、高頻率觸發事件的處理方案
下一篇:IE兼容/IE5兼容踩過的坑
