贵阳搜索玩的网站,东营网站seo外包,徐州网站制作需要多少钱,哈尔滨做网站的公司安装
使用命令 npm install lodash
页面引入
常见的引入方式
引入整个lodash对象#xff1a; import _ from lodash按名称引入特定的函数#xff1a; import { orderBy } from lodash; tips: 这两种引入方式都会引入整个lodash库#xff0c; 体积大#x…安装
使用命令 npm install lodash
页面引入
常见的引入方式
引入整个lodash对象 import _ from lodash按名称引入特定的函数 import { orderBy } from lodash; tips: 这两种引入方式都会引入整个lodash库 体积大不推荐
建议引入方式
只引入需要的函数 import orderBy from lodash/orderBy使用 lodash-es: import { orderBy } from lodash-es tips: 这两种方式只会引入对应的模块。
常用方法
concat
concat 创建一个新数组将原数组和任何数组或值连接在一起 用法
const array [1,3];
const newArray _.concat(array,4,7,[[8]]);
console.log(newArray) // [1,3,4,7,[8]];findIndex
findIndex 返回第一个判断为真值的元素的索引值。 用法 const arr [{name:judy,age: 12},{name:linda,age: 23},{name:candy,age: 43},{name:linda,age: 18},]const newArr _.findIndex(arr,function(o) {return o.name linda;})console.log(newArr); // 1const newArr1 _.findIndex(arr,{name: linda});console.log(newArr1) //1const newArr2 _.findIndex(arr,[name,linda]);console.log(newArr2,); //1orderBy
orderBy 对数组进行排序默认为升序也可以指定为 desc 降序或者指定为 asc 升序。 用法
const arr [{name:judy,age: 12},{name:linda,age: 23},{name:candy,age: 43},{name:cindy,age: 18},
]// 根据名字排序使用orderBy, 升序let arr1 _.orderBy(arr,[name],asc);console.log(arr1)// 根据名字排序使用orderBy, 降序let arr2 _.orderBy(arr,[name],desc);console.log(arr2)sample
sample 获得一个随机元素。 用法 const arr [ 1,2,3,4,5,6];const newArr _.sample(arr);console.log(newArr) // 随机返回了一个元素size
size 如果是数组或者字符串就返回 length ; 如果是对象返回其可枚举的属性个数 用法 const str string;console.log(_.size(str)); //6const arr [1,2,3,4];console.log(_.size(arr)); // 4const obj {name: linda,age: 24};console.log(_.size(obj)) // 2sortBy
sortBy 允许你指定一个属性来排序默认为升序。如果需要降序排需要借助reverse() 或者使用上方 orderBy 用法 const arr [{name:judy,age: 12},{name:linda,age: 23},{name:candy,age: 43},{name:cindy,age: 18},]// 根据名字排序使用sortBy 升序let arr3 _.sortBy(arr,[name]);console.log(arr3)// 根据名字排序使用sortBy先进性升序排序然后使用reverse()函数进行反转let arr4 _.sortBy(arr,[name]).reverse();console.log(arr4)debounce
debouncefunc,wait ,options 创建一个 debounced 防抖动函数该函数会从上一次被调用后延迟 wait 毫秒后调用 func 方法;可以提供一个 options选项 对象决定如何调用func方法。 用法
// 处理屏幕变化的函数const handle () {};// 使用debounce避免窗口在变动时消耗过大。window.addEventListener(resize,_.debounce(handle,3000))throttle
throttle(func,wait,options) 创建一个throttle节流函数在 wait 秒内最多执行 func 一次的函数。 用法
// 处理滚动事件const handleScroll () {};// 使用throttle避免窗口在变动时消耗过大。window.addEventListener(scroll,_.throttle(handleScroll ,3000))delay
delay 延迟多少时间后执行函数 使用 _.delay(function() {console.log(延迟执行了~~~)},500)clone
clone 创建一个 浅拷贝 使用 const arr [{name: linda,age: 13}];var newArr _.clone(arr);console.log(arr[0] newArr[0]); // truecloneDeep
cloneDeep 创建一个 深拷贝 使用 const arr [{name: linda,age: 13}];var newArr _.cloneDeep(arr);console.log(arr[0] newArr[0]); // false总结
更多lodash的方法及使用可以参考中文官网文档 https://www.lodashjs.com/