map()进每、filter()中都提供一個(gè)回調(diào)函數(shù),回調(diào)函數(shù)中有三個(gè)參數(shù)分別是數(shù)組元素腐巢,元素索引品追,原數(shù)組本身,并且這兩個(gè)方法在使用的過(guò)程中都不會(huì)改變?cè)瓟?shù)組冯丙。
一肉瓦、map()語(yǔ)法和示例
(1)、語(yǔ)法:
var newArray = arr.map(function callback(currentValue, index, array){
... //對(duì)每個(gè)元素的處理
})
參數(shù) :
1胃惜、callback:用來(lái)生成新數(shù)組用的函數(shù)泞莉。
2、currentValue:當(dāng)然正在處理的元素
3船殉、index:正在處理元素的索引
4鲫趁、array:調(diào)用map方法的數(shù)組(就是.map()前面的也就是arr)
(2)、示例
var a = [1,2,3,4];
var newa = a.map(function(x){
return x = x+1;
});
console.log(newa,a);
//newa : 2 3 4 5 //a: 1 2 3 4
二利虫、filter()語(yǔ)法和示例
filter()方法會(huì)返回一個(gè)新數(shù)組挨厚,該新數(shù)組的元素是符合回到函數(shù)中篩選條件的結(jié)果。filter()為數(shù)組中的每個(gè)元素調(diào)用一次 callback 函數(shù)糠惫,并利用所有使得回調(diào)函數(shù)返回 true 或等價(jià)于 true 的值的元素創(chuàng)建一個(gè)新數(shù)組疫剃;如果沒(méi)有任何的項(xiàng)符合篩選的條件(false),那么filter()方法將返回一個(gè)空的數(shù)組硼讽。
(1)巢价、語(yǔ)法:
var newArray = arr.filter(function callback(currentValue, index , array){
...//函數(shù)代碼
});
參數(shù) :
1、callback: 調(diào)用的過(guò)濾函數(shù)
2固阁、curValue: 當(dāng)前元素
3壤躲、index: 當(dāng)前元素的索引
4、array:調(diào)用filter的數(shù)組
(2)备燃、示例
var a = [1,2,3,4];
var newa = a.filter(function(x){
return x > 1;
});
console.log(newa,a);
//newa : 2 3 4 //a: 1 2 3 4
三碉克、兩者互換比較
把map中調(diào)用的函數(shù)換成filter里面的過(guò)濾函數(shù)是否能得到相同的結(jié)果
var a = [1,2,3,4];
var newa = a.map(function(x){
return x > 1;
});
console.log(newa,a);
//newa :false true true true //a: 1 2 3 4
可以看出來(lái)newa 的到的并不是數(shù)字,它們只是對(duì)當(dāng)前元素調(diào)用函數(shù)后(x是否大于1)的結(jié)果并齐。而filter 會(huì)將結(jié)果為true的數(shù)組存到新的數(shù)組里面棉胀。
四、與其他遍歷函數(shù)對(duì)比差異
(1)冀膝、forEach() 數(shù)組的每一個(gè)元素執(zhí)行一次提供的函數(shù)。
應(yīng)用一:
var a = [1,2,3,4];
var newa = a.forEach(function(x){
return x > 1;
});
console.log(newa,a); //undifined //1 2 3 4
應(yīng)用二:
var a = [1,2,3,4];
var newa = a.forEach(function(x){
console.log(x);
});
console.log(newa,a);
//1
//2
//3
//4
//undifined //1 2 3 4
從上面可以看出forEach 只是讓數(shù)組里面的元素執(zhí)行一次函數(shù)霎挟,并不會(huì)對(duì)原數(shù)組產(chǎn)生影響窝剖,也不會(huì)獲得新的數(shù)組
(2)、reduce() 接受一個(gè)函數(shù)作為累加器酥夭,依次加上數(shù)組的當(dāng)前元素赐纱。
語(yǔ)法
arr.reduce(callback(previousValue, currentValue, currentIndex,array),initialValue);
參數(shù)
1脊奋、callback:累加器函數(shù)
2、previousValue: 上一次調(diào)用函數(shù)后的返回值疙描,或者是提供的初始值(initialValue)
3诚隙、currentValue:當(dāng)前數(shù)組的元素
4、currentIndex:當(dāng)前數(shù)組元素的索引
5起胰、array:調(diào)用reduce的數(shù)組
6久又、initialValue:初始值,作為第一次調(diào)用callback的第一個(gè)參數(shù)效五,也可不寫地消,默認(rèn)為0;
示例
var a = [1,2,3,4];
var newa= a.reduce(function(total, current){
return total + current;
},100);
console.log(newa,a);
//110 //1 2 3 4
總結(jié):當(dāng)想改變數(shù)組的時(shí)候用map畏妖,想對(duì)數(shù)組進(jìn)行過(guò)濾用filter脉执,累加數(shù)組用reduce。
參考文章:https://blog.csdn.net/liuzm0515/article/details/80418801