<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Vue自學:javascript高階函數(shù)的使用</title>
<title></title>
</head>
<body>
</body>
<script type="text/javascript">
//所謂的高階函數(shù),就是傳遞的參數(shù)里,可以傳遞函數(shù),即function()
//編程范式分為命令式編程和聲明式編程
//變成方式:面相對象編程(第一公民:對象)、函數(shù)式編程(第一公民:函數(shù))
//高階函數(shù):filter map reduce
//filter 結果必須返回一個布爾值,假設返回的是個true時,函數(shù)內(nèi)部會自動將回調中的n存入到數(shù)組中,當返回為false時,函數(shù)內(nèi)部則會過濾掉這個n
//需求1,在數(shù)組中取出<100的數(shù)字
const nums = ['100','80','79','200','102','88']
//普通的執(zhí)行方法
// let result = []
// for(let item of nums){
// if(item<=100){
// result.push(item)
// }
// }
//filter 是一個高階函數(shù)
//函數(shù)的參數(shù)為一個函數(shù)
//filter會自動創(chuàng)建一個新的數(shù)組
//filter主要是對數(shù)組進行比較操作
let result = nums.filter(function(n){
return n<=100
})
console.log(result);
//map 高階函數(shù)
//map 主要將數(shù)組整合起來運算操作
let result1 = result.map(function(n){
return n*2
})
console.log(result1);
//reduce 高階函數(shù)的使用
//reduce 主要用于將數(shù)組整合操作
let result2 = result1.reduce(function(preValue,n){
return preValue+n
},0)
//第一次,preValue0 n200
//第二次, preValue200 n160
//第三次, preValue360 n158
//第四次, preValue518 n176
//結果為:518+176
//使用鏈式寫法
let result3 = nums.filter(function(n){
return n<=100
}).map(function(n){
return n*2
}).reduce(function(preValue,n){
return preValue+n
},0)
//使用箭頭函數(shù)的寫法
let result4 = nums.filter(n=> n<=100).map(n=> n*2).reduce((pre,n) => pre + n , 0)
console.log(result4)
</script>
</html>
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號