沐鳴註冊平台_JavaScript高階函數
概念
JavaScript中的函數本質上都指向某個變量,既然變量可以指向函數,函數的參數可以接受變量,那麼函數是不是可以可以作為另一個函數的入參?因為JavaScript是一門弱類型語言,不會對函數輸入值和函數的輸出值進行強定義和類型檢查。所以函數可以作為參數,也可以作為輸出值。
一個最簡單的高階函數:
let add=(x,y,f)=>f(x)+f(y);
對其他函數進行操作的函數,可以將他們作為參數或返回它們。
高階函數分類
- 函數作為參數傳遞
- 函數作為返回值
map/reduce/filter
map
定義:map() 方法返回一個新數組,不會改變原始數組。同時新數組中的元素為原始數組元素調用函數處理后的值,並按照原始數組元素順序依次處理元素。
語法:array.map(function(currentValue /*必填,當前元素的值 */,index /*可選,當前元素的索引*/,arr /*可選,當前元素屬於的數組對象*/), thisValue /*可選,上下文對象,用作this,默認為全局對象*/)
有以下需求:創建一個新數組,其中的值是原數組的值的兩倍。
const arr=[1,2,3]
let fn=(arr)=>{
let temp=[]
for(let i=0;i<arr.length;i++){
temp.push(arr[i]*2)
}
return temp;
}
console.log(fn(arr))
以上是我們的命令式編程,我們改寫下:
const temp=[1,2,3].map(item=>item*2)
console.log(temp)
在這裏我們使用(item)=>item*2作為map函數的參數。
手動實現map(),遍歷函數的每一項作為函數的入參,並返回每次函數調用結果組成的數組
關鍵:1.函數為空,返回空 2.func 必須是函數類型,需要有return值,否則會出現所有項映射為undefind 3.無副作用
Array.prototype.mapTest = function (func, content) {
if (typeof func !== 'function') throw new TypeError(
`${typeof func} is not a function`)
let arrTemp = this.slice()
content = typeof content === 'undefined' ? null : content
let result = []
for (let idx = 0; idx < arrTemp.length; idx++) {
result.push(func.call(content, arrTemp[idx], idx, arrTemp))
}
return result
}
reduce
定義:reduce() 方法接收一個函數作為累加器,數組中的每個值(從左到右)開始縮減,最終計算為一個值
語法:array.reduce(function(total /*必需。初始值, 或者計算結束后的返回值*/, currentValue/*必需。當前元素*/, currentIndex/*可選。當前元素的索引*/, arr/*可選。當前元素所屬的數組對象。*/), initialValue/*可選。傳遞給函數的初始值*/)
有以下需求:對數組arr的項進行求和
let arr=[1,2,3,4]
// 命令式編程
let sum=arr=>{
let temp=0;
for(let idx=0;idx<arr.length;idx++){
temp+=arr[idx]
}
return temp
}
//使用reduce
let total=arr.reduce((prev,cur)=>{
return prev+cur
},0)
過程分析:
第一次執行時,prev的值為我們的初始值0,返回0+cur(當前數組的第一位)作為第二次執行時的prev….從而達到累加的目的;
手動實現一個reduce(),核心就是遍曆數組每一項參与函數運算並將返回值作為下次遍歷的初始值,從而實現累加。
關鍵點
:1.無初始值時,從原數組的第二項進行遍歷
2.無副作用
Array.prototype.reduceTest = function(func, initVal, directionLeft = true) {
if (typeof func !== 'function') throw new TypeError(`${typeof func} is not a function`)
if (!this.length) {
if (typeof initVal !== 'undefined') {
return initVal
} else {
throw new Error('Reduce of empty array with no initial value')
}
}
let array = this.slice()
let hasInitVal = typeof initVal !== 'undefined'
let value = hasInitVal ? initVal : array[0]
if (directionLeft === false) {
array = array.reverse()
}
for (let idx = hasInitVal ? 0 : 1; idx < array.length; idx++) {
const cur = array[idx]
value = func.call(null,value, cur, idx, array)
}
return value
}
filter
定義:filter() 方法創建一個新的數組,新數組中的元素是通過檢查指定數組中符合條件的所有元素。
語法:array.filter(function(currentValue/*必須。當前元素的值*/,index/*可選。當前元素的索引值*/,arr/*可選。當前元素屬於的數組對象*/), thisValue/*可選。對象作為該執行回調時使用,傳遞給函數,用作 “this” 的值*/)
需求:過濾出對象數組中age大於10的元素
let persons = [
{ 'name': 'Bob', age: 12 },
{ 'name': 'Lily', age: 13 },
{ 'name': 'Tom', age: 9 },
{ 'name': 'Jone', age: 99 },
]
// 命令式編程
let result=()=>{
let res=[];
for(let idx=0;idx<persons.length;idx++){
if(persons[idx].age>10){
res.push(persons[idx])
}
}
return res;
}
// 使用filter
let filterResult=persons.filter(item=>item.age>9);
手動實現一個filter(),核心就是創建一個新的數組,新數組中的元素是原數組中符合條件的項。
關鍵點
:1.函數返回值為true/false 2.無副作用
Array.prototype.filterTest=function (func,content) {
if (typeof func !== 'function') throw new TypeError(`${typeof func} is not a function`)
if (!this.length) return []
content = typeof content === 'undefined' ? null : content
let result=[]
for(let idx=0;idx<arr.length;idx++){
let res=func.call(content,arr[idx],idx,arr)
if(res){
result.push(arr[idx])
}
}
return result
}
flat
注意:普通瀏覽器(僅Chrome v69,Firefox Nightly和Opera 56等)/Node.js (需V11.0.0及以上) 尚未實現flat方法。這是一項實驗性功能。 [MDN 說明以及替代方案]
用法:將目標嵌套數組扁平化,變為新的一維數組
語法:arrry.flat([depth]/*指定要提取嵌套數組的結構深度,默認值為 1。Infinity為無限*/)
手動實現一個flat()
/**
* 數組扁平化
* @param depth 拉平深度 默認為1,最大為Infinity
*/
Array.prototype.flatTest = function (depth = 1) {
let arr = this.slice()
const result = []
// 當前已拉平層數
let flattenDepth = 1;
// 先拉平第一層
(function flatten (list) {
list.forEach((item) => {
if (flattenDepth < depth &&Array.isArray(item)) {
flattenDepth++
flatten(item)
} else {
result.push(item)
}
})
})(arr)
return result
}
總結
高階函數本質上就是對算法的高度抽象,通過提高抽象度,實現最大程度代碼重構。
站長推薦
1.雲服務推薦: 國內主流雲服務商,各類雲產品的最新活動,優惠券領取。地址:阿里雲騰訊雲華為雲
2.廣告聯盟: 整理了目前主流的廣告聯盟平台,如果你有流量,可以作為參考選擇適合你的平台點擊進入
鏈接: http://www.fly63.com/article/detial/8154