lodash工具库

2023-06-01 00:00:00 lodash 工具

Lodash 是一个一致性、模块化、高性能的 JavaScript 实用工具库。

Lodash 通过降低 array、number、objects、string 等等的使用难度从而让 JavaScript 变得更简单。 

Lodash 的模块化方法 非常适用于:

遍历 array、object 和 string
对值进行操作和检测
创建符合功能的函数


官方文档:

https://www.lodashjs.com/


安装

npm install lodash --save
or
arn add lodash

浏览器环境直接引入:

<script src="lodash.js"></script>

Node.js:

// Load the full build.
var _ = require('lodash');
// Load the core build.
var _ = require('lodash/core');
// Load the FP build for immutable auto-curried iteratee-first data-last methods.
var fp = require('lodash/fp');
 
// Load method categories.
var array = require('lodash/array');
var object = require('lodash/fp/object');
 
// Cherry-pick methods for smaller browserify/rollup/webpack bundles.
var at = require('lodash/at');
var curryN = require('lodash/fp/curryN');

使用

import {debounce, isString, isUndefined, isNaN, map} from 'lodash'


防抖函数:debounce

// 避免窗口在变动时出现昂贵的计算开销。
jQuery(window).on('resize', _.debounce(calculateLayout, 150));
 
// 当点击时 `sendMail` 随后就被调用。
jQuery(element).on('click', _.debounce(sendMail, 300, {
  'leading': true,
  'trailing': false
}));
 
// 确保 `batchLog` 调用1次之后,1秒内会被触发。
var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
var source = new EventSource('/stream');
jQuery(source).on('message', debounced);
 
// 取消一个 trailing 的防抖动调用
jQuery(window).on('popstate', debounced.cancel);


节流函数:throttle

import _ from 'lodash'
// 触发后,5秒内不在执行,5秒结束后会再执行一次
_.throttle(updatePosition, 5000)
// 5秒内只触发一次
_.throttle(renewToken, 5000, { 'trailing': false }


深克隆函数:cloneDeep

var objects = [{ 'a': 1 }, { 'b': 2 }];
 
var deep = _.cloneDeep(objects);
console.log(deep[0] === objects[0]);
// => false

补充工具:

futil-js是一套用来补足 lodash 的实用工具集。


兼容性

在Chrome 74-75、Firefox 66-67、IE 11、Edge 18、Safari 11-12 和 Node.js 8-12 环境中测试通过。

相关文章