前言
需求:有這樣一個數組[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)
參數說明如下:
- function(currentValue, index, arr):必填函數,數組中的每個元素都會執行這個函數
- 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:必填。初始值, 或者計算結束后的返回值。
- currentValue:必填,當前元素的值
- index:可選。當前元素的索引值
- arr:可選。當前元素屬於的數組對象
- 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循環了