Array.prototype.map()
創(chuàng)建一個(gè)新的數(shù)組,其結(jié)果是該數(shù)組中每個(gè)元素都調(diào)用一個(gè)提供的函數(shù)后返回的結(jié)果。
語(yǔ)法:
var newArray = arr.map(function callback(currentValue, index, array){
//對(duì)每個(gè)元素的處理
})
參數(shù)
callback:用來(lái)生成新數(shù)組用的函數(shù)堕花。
callback的參數(shù):
currentValue:當(dāng)然正在處理的元素
index:正在處理元素的索引
array:調(diào)用map方法的數(shù)組(就是.map()前面的也就是arr)
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
Array.prototype.filter()
創(chuàng)建一個(gè)新數(shù)組阶祭,其結(jié)果是調(diào)用一個(gè)函數(shù)后過(guò)濾得的元素缆毁。
語(yǔ)法
var newArray = arr.filter(function callback(curValue, index , array){
//函數(shù)代碼
});
參數(shù)
callback: 調(diào)用的過(guò)濾函數(shù)
curValue: 當(dāng)前元素
index: 當(dāng)前元素的索引
array:調(diào)用filter的數(shù)組
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
基本用法就是以上那些
因?yàn)槎际菍?duì)元素的遍歷荔棉,所以我猜想 如果把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ù)組里面。
Array.prototype.forEach()
數(shù)組的每一個(gè)元素執(zhí)行一次提供的函數(shù)爸舒。
var a = [1,2,3,4];
var newa = a.forEach(function(x){
return x > 1;
});
console.log(newa,a); //undifined //1 2 3 4
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ù)組
Array.prototype.reduce()
接受一個(gè)函數(shù)作為累加器碳抄,依次加上數(shù)組的當(dāng)前元素愉老。
語(yǔ)法
arr.reduce(callback(previousValue, currentValue, currentIndex,array),initialValue);
參數(shù)
callback:累加器函數(shù)
previousValue: 上一次調(diào)用函數(shù)后的返回值场绿,或者是提供的初始值(initialValue)
currentValue:當(dāng)前數(shù)組的元素
currentIndex:當(dāng)前數(shù)組元素的索引
array:調(diào)用reduce的數(shù)組
initialValue:初始值剖效,作為第一次調(diào)用callback的第一個(gè)參數(shù)嫉入,也可不寫(xiě),默認(rèn)為0璧尸;
var a = [1,2,3,4];
var new = a.reduce(function(total, current){
return total + current;
},100);
console.log(new,a);
//10 //1 2 3 4