前言
需求:有這樣一個數組
[10, 20, 110, 200, 60, 30, 40]
1.篩選出數組中小于100的元素
2.将篩選出的每個元素的值x2
3.完成第2步之後,将數組中的所有元素加起來
普通方法
如果我們還沒接觸過
filter
、
map
reduce
,那麼就是用
for
循環
<script>
list = [10, 20, 30, 40, 60, 110, 200]
newList = []
newList2 = []
total = 0
// 第1次for循環把小于100的數加入新的數組newList
for (item of list){
if (item<100){
newList.push(item)
}
}
// 第2次for循環把所有的元素值乘以2
for (item of newList){
newValue = item * 2
newList2.push(newValue)
}
// 第3次for循環把數組中的全部元素加起來
for (item of newList2){
total += item
}
console.log(total)
</script>
以上寫起來非常繁瑣,還要定義很多變量,代碼閱讀起來也不是很好,其實我們有更好的方式,下面介紹
filter
檢測數值元素,并傳回符合條件所有元素的數組。
定義和用法
filter()
方法建立一個新的數組,新數組中的元素是通過檢查指定數組中符合條件的所有元素
注意
filter()
不會對空數組進行檢測。
filter()
不會改變原始數組。
文法
array.filter(function(currentValue,index,arr), thisValue)
參數說明如下:
- function(currentValue, index, arr):必填函數,數組中的每個元素都會執行這個函數
- currentValue:必填,目前元素的值
- index:可選。目前元素的索引值
- arr:可選。目前元素屬于的數組對象
- thisValue:可選。對象作為該執行回調時使用,傳遞給函數,用作
的值。如果省略了this
,thisValue
的值為this
undefined
小練習
使用
filter
函數篩選出
[10, 20, 110, 200, 60, 30, 40]
小于100的
list = [10, 20, 30, 40, 60, 110, 200]
newList = list.filter(function (n) {
return n < 100
})
console.log(newList)
列印結果
[10, 20, 30, 40, 60]
map
通過指定函數處理數組的每個元素,并傳回處理後的數組。
map()
方法傳回一個新數組,數組中的元素為原始數組元素調用函數處理後的值。
map()
方法按照原始數組元素順序依次處理元素。
注意:
map()
map()
array.map(function(currentValue,index,arr), thisValue)
-
-
this
,或者傳入thisValue
null
,那麼回調函數的undefined
為全局對象。this
将數組
[10, 20, 30, 40, 60]
中的每個元素值乘以2
<script>
list = [10, 20, 30, 40, 60]
newList = list.map(function (n) {
return n * 2
})
console.log(newList)
</script>
[20, 40, 60, 80, 120]
reduce
将數組元素計算為一個值(從左到右)
reduce()
方法接收一個函數作為累加器,數組中的每個值(從左到右)開始縮減,最終計算為一個值。
reduce()
可以作為一個高階函數,用于函數的
compose
。
注意:
reduce()
對于空數組是不會執行回調函數的。
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
- function(total,currentValue, index,arr):必填函數,數組中的每個元素都會執行這個函數
- total:必填。初始值, 或者計算結束後的傳回值。
- initialValue:可選。傳遞給函數的初始值
計算數組之和
[20, 40, 60, 80, 120]
<script>
list = [20, 40, 60, 80, 120]
newList = list.reduce(function (total, n) {
return total + n
}, 0)
console.log(newList)
</script>
320
使用filter和map和reduce完成案例
上面我們分别介紹了3個高階函數,接下來結合起來使用
方式1
<script>
list = [10, 20, 110, 200, 60, 30, 40]
newList = list.filter(function (n) {
return n < 100
}).map(function (n) {
return n * 2
}).reduce(function (total, n) {
return total + n
})
console.log(newList)
</script>
方式2
<script>
list = [10, 20, 110, 200, 60, 30, 40]
newList = list.filter(n => n < 100).map(n => n * 2).reduce((total, n) => total+n);
console.log(newList)
</script>
以後我們就可以一行代碼完成上面的需求,而不需要使用for循環了