1.官网lodash.com 包括FP Guide(函数式编程指导)及文档(介绍了lodash所有的函数)
2.安装教程
(1)打开vscode,初始化packge.json.
终端输入npm init -y
(2)安装lodash
终端输入npm install lodash
(3)引用lodash
const =require(‘lodash’)
(4)使用方法
const _ = require(‘lodash’)
const arr = [‘jack’,‘tom’,‘jam’]
console.log(.first(arr))
console.log(.last(arr))
console.log(.reverse(arr))
结果:
注意:lodash中的reverse方法会改变原数组,它不是一个纯函数。
lodash中的FP模块里的函数才是纯函数。
3.纯函数的好处
1.可缓存(因为具有相同的输出)
通过缓存提高性能
使用memoize进行缓存
function getArea®
{
return Math.PI * r * r
}
let getAreaWithMemory = _.memoize(getArea)
//模拟memoize方法的实现
function memoize(f){
let cache={}
return function(){
let key = JSON.stringify(arguments)
cache[key] = cache[key] || f.apply(f,arguments)//获取缓存是否有值,有就返回cache,如果没有就调用f函数
return cache[key]
}
}
lodash学习笔记
最新推荐文章于 2024-04-06 11:19:51 发布