1. 程式人生 > 實用技巧 >陣列的forEach方法和map方法

陣列的forEach方法和map方法

forEach

定義:forEach是給陣列的每一個元素執行一次給定的函式

語法

arr.forEach(callback(currentValue [, index [, array]])[, thisArg])

引數

callback

為每個元素執行的函式,該函式接收三個引數
currentValue

陣列中正在處理的當前元素

index

陣列中正在處理的當前元素的索引

array

函式正在操作的陣列

thisArg

可選引數,當執行callback時,用作this的值
例子

var thisArg = {a:1,b:2,c:3}
var arr = [1,2,34,56,665,434];
arr.forEach(function(item,index,arrValue){
    console.log(item)
    console.log(index)
    console.log(arrValue)
    console.log(this)
    item = item * 2
},thisArg)

執行結果

從上面結果中,我們可以發現,使用forEach遍歷陣列,可以給forEach傳一個函式,該函式是當前元素執行的函式,它接收三個引數分別是陣列的當前執行元素的值,當前執行元素的索引,forEach的第二個引數就是在函式中的上下文 this的指向,函式的forEach沒有返回值
,同時,執行了callback函式後,原陣列也不會發生改變

陣列的map方法

定義:map方法返回一個新陣列,新陣列的值為原始陣列呼叫函式處理後的值

map方法陣列按照原始陣列元素順序依次處理元素

map方法不會處理空陣列

map方法不會改變原始陣列

語法

array.map(function(currentValue,index,arr), thisValue)

引數說明

function(currentValue, index,arr)

陣列中每個元素都會執行的函式,其中函式的引數
currentValue:當前執行函式的陣列元素

index:當前執行函式的陣列元素的索引

arr:當前被操作的陣列

thisValue

用作執行函式的上下文,未定型或者沒傳,為window

例子

var newArr = arr.map(function(item,index,arrValue){
    console.log(item,index)
    
    console.log(arrValue)
    console.log(this)
    return item*2
},thisArg)
console.log(newArr)
console.log(arr)

執行結果