1、闭包

函数在执行的时候,会放到一个执行栈上,当函数执行完毕之后,会从执行栈上移除,但是堆上的作用域成员因为被外部引用不能释放,因此内部函数依然可以访问函数的成员

2、纯函数

定义:相同的输入永远会得到相同的输出

slice:是纯函数

splice:不是纯函数

3、lodash

初始化package.json

npm init -y

安装lodash

npm i lodash

 

演示:lodash

// first / last / toUpper / reverse / each / includes / find / findIndex

const _ = require('lodash');
const array = ['jack', 'tom', 'lucy', 'kate'];
console.log(_.first(array));  //第一个元素
console.log(_.last(array)); //最后一个元素
console.log(_.toUpper(_.first(array))); //第一个元素转大写
console.log(_.reverse(array)); //将数组数据倒叙
const r = _.each(array, (item,index) => {
    console.log(item,index)
});
console.log(r)

4、纯函数的好处

(1)记忆函数

const _ = require('lodash');
function getArea(r){
    return Math.PI * r * r;
}
let getAreaWithMemory = _.memoize(getArea);
console.log(getAreaWithMemory(4))

5、函数柯里化

概念:当一个函数有多个参数的时候先传递一部分参数调用它(这部分参数永远不变);

然后返回一个新的函数接收剩余的参数,返回结果

function checkAge(min){
    return function(age){
        return age>=min;
    }
}
const min1 = checkAge(18);
console.log(min1(22));
const min2 = checkAge(16);
console.log(min2(18))
//用箭头函数表示
let checkAge = min => (age => age>=min)
const min1 = checkAge(18);
console.log(min1(20));
 //多个参数
let getSum = a => (b => (c => a+b+c));
const sum1=getSum(3);
const getSum1 = sum1(4);
console.log(getSum1(2));

6、lodash中的柯里化函数

const _ = require('lodash');
let getSum = (a,b,c) => a+b+c;
const curried = _.curry(getSum);
console.log(curried(1,2,3))
let cur1 = curried(1);
console.log(cur1(1,1))
console.log(curried(1)(2,2));

7、柯里化案例

柯里化函数在有多个参数时,可以想传几个参数传几个参数,但是求结果的总参数需要和调用函数的参数个数一致;

就是说,所有的参数可以分批传,但是求结果的话,需要传完

const match = _.curry(function(reg,str){
    return str.match(reg);
})
const haveSpace = match(/\s+/g);
console.log(haveSpace('hello world'))
const haveSpace1 = match(/\s+/g,'hello world');
console.log(haveSpace1);
// 转成箭头函数
const match1 = _.curry((reg,str) => str.match(reg))
const haveSpace = match1(/\s+/g);
console.log(haveSpace('hello world'))
 
 
posted on 2021-01-25 15:49  phantom_yy  阅读(169)  评论(0)    收藏  举报