1 //高阶函数:一个函数可以接受另一个函数作为参数,这种函数称之为高阶函数。 2 /*1*/ 3 function f(x,y,f){ 4 return f(x)+f(y); 5 } 6 var sumAbs=f(-6,4,Math.abs); 7 console.log(sumAbs);//10 8 9 10 11 //map和reduce12 /*map*/13 /*2*/14 function pow(x){15 return x*x;16 }17 var arr=[1,2,3,4,5];18 var x2=arr.map(pow);19 var toS=arr.map(String);20 console.log(x2);//[1, 4, 9, 16, 25]21 console.log(toS);//["1", "2", "3", "4", "5"]22 23 24 /*reduce*/25 /*3*/26 var arr=[1,3,5,7,9];27 function sum(x,y){28 return x+y;29 }30 function pro(x,y){31 return x*y;32 }33 function intt(x,y){34 return x*10+y;35 }36 var s=arr.reduce(sum);37 var p=arr.reduce(pro);38 var i=arr.reduce(intt);39 console.log(s);//2540 console.log(p);//94541 console.log(i);//1357942 43 /*or*/44 console.log(arr.reduce(function(x,y){45 return x+y;46 }));//2547 console.log(arr.reduce(function(x,y){48 return x*y;49 }));//94550 console.log(arr.reduce(function(x,y){51 return x*10+y;52 }));//1357953 54 55 /*string to int*/56 /*4*/57 var str="5678";58 var arr=str.split('');59 console.log(arr);//["5", "6", "7", "8"]60 arr=arr.map(function(x){61 return x-0;62 })63 console.log(arr);//[5, 6, 7, 8]64 console.log(arr.reduce(function(x,y){65 return x*10+y;//567866 }))67 68 /*or*/69 console.log(str.split('').map(function(x){70 return x-0;71 }).reduce(function(x,y){72 return x*10+y;73 }));//567874 75 76 /*请把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']。*/77 78 /*test*/79 var str="abs";80 console.log(str[0]);//a81 /*5*/82 var arr=['adam', 'LISA', 'barT'];83 console.log(arr.map(function(x){84 return x[0].toUpperCase()+x.substring(1).toLowerCase()85 }));// ["Adam", "Lisa", "Bart"]