js高阶函数
高阶函数( Higher-order function ):JavaScript的一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。
例子:
function addition(x,y,z) { return z(x) + z(y); } addition(-3, -4, Math.abs); // ==> Math.abs(-3) + Math.abs(-4) ==> 7
JavaScript中的内置高阶函数:
1. map(); // array.map(callback,[ thisObject]);
例子:
const arr = [1, 2, 3]; const newArr = arr.map(item => item * 2); console.log(newArr); //[2, 4, 6]
2. reduce(); // array.reduce(function(total, currentValue, currentIndex, arr), initialValue);
例子:
const arr = [1, 2, 3]; let sum = arr.reduce((accumulator, currentValue, currentIndex, array) => { return accumulator + currentValue; }); console.log(sum); // 10
const arr = [1, 2, 3]; let sum1 = arr.reduce((accumulator, currentValue, currentIndex, array) => { return accumulator + currentValue; }, 10); console.log(sum1); // 20
3. filter(); // array.filter(callback(element[, index[, array]])[, thisArg])
例子:
const arr = [1, 1, 2, 2, 3, 4, 3, 4, 5, 5, 4]; const newArr = arr.filter((ele, index, self) => { return self.indexOf(ele) === index; }); console.log(newArr); // [1, 2, 3, 4, 5]
4. sort(); // arr.sort([compareFunction])
例子:
const arr = [1, 20, 10, 5]; let compareNumbers= function (a, b) { return a - b; } const newArr = arr.sort(compareNumbers); console.log(newArr); // [1, 5, 10, 20]
———————————— 方向错了,停下来就是进步 ————————————