js中 .map()和.filter()以及他們的區別
今天看到朋友寫的一個數組對比,用的filter(),於是就想想起map(),都是對內部的元素一個一個去遍歷,然后輸出,到底有什么區別的。
先說下,jquery也有這兩個方法,不過大家都懂得,他們都是對JavaScript進行的封裝,我這里只說下JavaScript的。
我們說的map()和filter()其實是:
Array.prototype.map()
創建一個新的數組,其結果是該數組中每個元素都調用一個提供的函數后返回的結果。
語法:
var newArray = arr.map(function callback(currentValue, index, array){
//對每個元素的處理
})
參數
callback:用來生成新數組用的函數。
callback的參數:
currentValue:當然正在處理的元素
index:正在處理元素的索引
array:調用map方法的數組(就是.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
- 1
- 2
- 3
- 4
- 5
- 6
Array.prototype.filter()
創建一個新數組,其結果是調用一個函數后過濾得的元素。
語法
var newArray = arr.filter(function callback(curValue, index , array){
//函數代碼
});
參數
callback: 調用的過濾函數
curValue: 當前元素
index: 當前元素的索引
array:調用filter的數組
-
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
- 1
- 2
- 3
- 4
- 5
- 6
基本用法就是以上那些
因為都是對元素的遍歷,所以我猜想 如果把map中調用的函數換成filter里面的過濾函數是否能得到相同的結果呢。
於是
-
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
- 1
- 2
- 3
- 4
- 5
- 6
可以看出來newa 的到的並不是數字,它們只是對當前元素調用函數后(x是否大於1)的結果。而filter 會將結果為true的數組存到新的數組里面。
另外還有兩個常用的遍歷函數
Array.prototype.forEach()
數組的每一個元素執行一次提供的函數。
-
var a = [
1,
2,
3,
4];
-
var newa = a.
forEach(
function(x){
-
return x >
1;
-
});
-
console.log(newa,a);
//undifined //1 2 3 4
- 1
- 2
- 3
- 4
- 5
-
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
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
從上面可以看出forEach 只是讓數組里面的元素執行一次函數,並不會對原數組產生影響,也不會獲得新的數組
Array.prototype.reduce()
接受一個函數作為累加器,依次加上數組的當前元素。
語法
arr.reduce(callback(previousValue, currentValue, currentIndex,array),initialValue);
參數
callback:累加器函數
previousValue: 上一次調用函數后的返回值,或者是提供的初始值(initialValue)
currentValue:當前數組的元素
currentIndex:當前數組元素的索引
array:調用reduce的數組
initialValue:初始值,作為第一次調用callback的第一個參數,也可不寫,默認為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
- 1
- 2
- 3
- 4
- 5
- 6
其實上面介紹的全是遍歷函數,但都有細微的差別,每個都各司其職(好像有點廢話),所以當想改變數組的時候用map,想對數組進行過濾用filter,累加數組用reduce。
不過看了上面的概念和栗子,我想你能更准確的使用它們,那么沒問題了,哈哈。
如有錯誤請指出,前端小白在學習。