首先是函數概述:
map():返回一個新的Array,每一個元素爲調用func的結果
filter():返回一個符合func條件的元素數組
some():返回一個boolean,判斷是否有元素是否符合func條件
every():返回一個boolean,判斷每一個元素是否符合func條件
forEach():沒有返回值,只是針對每一個元素調用func
reduce():有返回值,重點是計算數組,返回一個值
其次
一、map速度比forEach快
二、map會返回一個新數組,不對原數組產生影響,foreach不會產生新數組,
三、map由於返回數組因此能夠鏈式操做,forEach不能javascript
filter
語法java
var new_arr = arr.filter(callback(element, index, array){ }, this)
參數:callback 回調數組
element 當前的value index 當前的索引值 array arr這個數組對象 this 回調的this指向
用法
//若是返回值是true的話,就是符合條件。
//filter 不會改變原數組,它返回過濾後的新數組。
//這個裏返回數組裏面的偶數
[10,11,12,13].filter((v)=>v % 2 == 0)
場景
場景就是過濾,把符合條件的整理到一塊兒,常見的就是展現審覈經過的數據函數
forEach
語法this
arr.forEach(callback(element, index, array){ }, this)
參數:callback 回調code
element 當前的value index 當前的索引值 array arr這個數組對象 this 回調的this指向
用法
//遍歷數組。打印到控制檯對象
[10,11,12,13].forEach((v)=>{ console.log(v) })
// 成功的收集到success裏面,錯誤的收集到error裏面。索引
var success = [],error = []; [{state:1},{state:0},{state:0},{state:0}].forEach((v)=>{ if(v.state == 1){ success.push(v) }else{ error.push(v) } })
場景
好比說綁定事件,好比判斷值而後push到不一樣的地方事件
map
語法ip
arr.map(callback(element, index, array){ }, this)
參數:callback 回調
element 當前的value index 當前的索引值 array arr這個數組對象 this 回調的this指向
用法
//把數值格式化,保留兩位小數
[10.055,11.054,12.056,13.789].map((v)=>+v.toFixed(2))
場景
這個通常就用在,我須要一組值,可是這個值不對,須要計算原數組來生成。
reduce
語法
arr.reduce(callback(accumulator, element, index, array){ }, initialValue)
參數:callback 回調
sum 累加器的返回值,也就是上一次回調的返回值 element 當前的value index 當前的索引值 array arr這個數組對象 initialValue 初始傳入的值,若是不傳回調從下標1開始,下標0做爲初始值
用法
//累加
[10,11,12,13].reduce((s,v)=>s+v,0)
場景
這個計算整個數組得出一個值的
some
語法
arr.some(callback(element, index, array){ }, this)
參數:callback 回調
element 當前的value index 當前的索引值 array arr這個數組對象 this 回調的this指向
用法
initArray = initArray.some(item => { if (item === 1){ return true } return false })
場景
這個通常就用在,判斷數組裏是否有某個值。
every
語法
arr.every(callback(element, index, array){ }, this)
參數:callback 回調
element 當前的value index 當前的索引值 array arr這個數組對象 this 回調的this指向
用法
initArray = initArray.every(item => { if (item === 1){ return true } return false })
場景這個通常就用在,判斷數組的每一個元素是否符合func條件。