lodash使用

Lodash工具库小记

项目中可以用工具安装

npm install lodash
# 或者
pnpm install lodash

// 引入整个Lodash
import _ from 'lodash';
// 只引入需要的模块
import { debounce } from 'lodash';

或者直接cdn引入

<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
differenceWith返回一个过滤值后的新数组
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let temp = [1, 2, 3, 4, 5]
let reverseArr = _.differenceWith(arr, temp)
console.log(reverseArr)
//得到结果[6, 7, 8, 9, 10]
//第三个参数,可以回调函数
orderBy对对象数组以指定字段进行排序
let arrOrder = [{ id: 1, name: 'n' }, { id: 3, name: 'm' }, { id: 2, name: 'a' }, { id: 5, name: 'e' }]
let newArr = _.orderBy(arrOrder, ['id'], ['asc']);
console.log(newArr)
//得到结果[
//   {id: 1, name: 'n'},
//   {id: 2, name: 'a'},
//   {id: 3, name: 'm'},
//   {id: 5, name: 'e'},
// ];
uniqby可以用于通过主键去重
let arrUniq = [
    {id:1,value:'q'},
    {id:2,value:'w'},
    {id:3,value:'e'},
    {id:1,value:'q'},
    {id:2,value:'w'},
    {id:3,value:'e'},
]
let newUniq = _.uniqBy(arrUniq,'id')
console.log(newUniq)
//得到结果[
//{id:1,value:'q'},
//{id:2,value:'w'},
//{id:3,value:'e'},
//]
max取数组最大值
let result = _.max([4, 2, 8, 6]);
console.log(arr)
//得到结果8
debounce防抖
onChange:_.debounce( e => {
    formModel.jsje = Number(e) * Number(formModel.jssl)
},500)
在UniApp中使用Lodash库可以方便地进行数据处理和操作。Lodash是一个JavaScript实用工具库,提供了很多常用的函数方法,可以简化开发过程并提高代码的可读性和可维护性。 要在UniApp中使用Lodash,首先需要安装Lodash库。可以通过npm安装,打开终端并执行以下命令: ``` npm install lodash ``` 安装完成后,在需要使用Lodash的页面或组件中引入Lodash库: ```javascript import _ from 'lodash'; ``` 接下来就可以使用Lodash提供的各种函数方法了。以下是一些常用的Lodash函数方法示例: 1. 数组操作: ```javascript const arr = [1, 2, 3, 4, 5]; // 使用Lodash的map函数对数组进行映射操作 const mappedArr = _.map(arr, (num) => num * 2); console.log(mappedArr); // [2, 4, 6, 8, 10] // 使用Lodash的filter函数对数组进行过滤操作 const filteredArr = _.filter(arr, (num) => num % 2 === 0); console.log(filteredArr); // [2, 4] ``` 2. 对象操作: ```javascript const obj = { name: 'Alice', age: 20, gender: 'female' }; // 使用Lodash的pick函数选择对象的指定属性 const pickedObj = _.pick(obj, ['name', 'age']); console.log(pickedObj); // { name: 'Alice', age: 20 } // 使用Lodash的omit函数忽略对象的指定属性 const omittedObj = _.omit(obj, ['gender']); console.log(omittedObj); // { name: 'Alice', age: 20 } ``` 3. 字符串操作: ```javascript const str = 'Hello, World!'; // 使用Lodash的toUpper函数将字符串转为大写 const upperStr = _.toUpper(str); console.log(upperStr); // 'HELLO, WORLD!' // 使用Lodash的truncate函数截断字符串 const truncatedStr = _.truncate(str, { length: 10 }); console.log(truncatedStr); // 'Hello, Wor...' ``` 这些只是Lodash提供的众多函数方法中的一部分,你可以根据具体需求查阅Lodash官方文档来了解更多用法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值