1、高階函數是至少知足下列一個條件的函數:javascript
接受一個或多個函數做爲輸入java
返回一個函數數組
2、js中高階函數函數
一、reduceui
var arr = [1,3,5,7,9]; function add(x,y){ return x+y; } var results = arr.reduce(add); console.log(results); //25
二、mapthis
function pow(x){ return x*x; } var arr = [1,2,3,4,5,6]; var results = arr.map(pow); console.log(results); //[1,4,9,16,25,36]
嘗試本身DIY一個mapspa
var arr = {
a:[1,2,3,4,5,6],
map:function(callback){
var temp = [];
for(var i in this.a){
temp.push(callback(this.a[i]))
}
return temp;
}
}
function pow(x){
return x*x;
}
var results = arr.map(pow);
console.log(results); //[1,4,9,16,25,36]
三、filterblog
var arr = [2,4,1,7,2,3]; function go(x){ return x>=4; } var results = arr.filter(go); console.log(results); //[4,7]
四、sort排序
var arr = [3,1,2,0,12]; function look(x,y){ return y-x; } var results = arr.sort(look); console.log(results); //[12, 3, 2, 1, 0]
查閱資料:V8 引擎 sort 函數只給出了兩種排序 InsertionSort 和 QuickSort,數組長度小於等於 22 的用插入排序 InsertionSort,比22大的數組則使用快速排序 QuickSortip