Happy New Year!

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]);

了解更多map方法

例子:

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); 

了解更多reduce方法

例子:

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])

了解更多filter方法

例子:

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])

了解更多sort方法

例子:

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]

 

posted @ 2020-03-01 19:52  一只看夕阳的猫  阅读(2048)  评论(0编辑  收藏  举报
返回顶部小火箭
世界很公平,想要最好,就一定得付出!
x
博客主页