Lodash工具库

官方地址

https://www.lodashjs.com/

简介

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

Lodash 遵循 MIT 开源协议发布,并且支持最新的运行环境。 查看各个构件版本的区别并选择一个适合你的版

安装

浏览器环境:

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

通过 npm:

1
2
$ npm i -g npm
$ npm i --save lodash

Node.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 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');

注意:

如需在 Node.js < 6 的 REPL 环境中使用 Lodash,请安装 n_

Lodash 通过降低 array、number、objects、string 等等的使用难度从而让 JavaScript 变得更简单。 Lodash 的模块化方法 非常适用于:

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

好用的函数

_.debounce 防抖动

是一个通过 Lodash 限制操作频率的函数。   // 在这个例子中,我们希望限制访问 yesno.wtf/api 的频率   // AJAX 请求直到用户输入完毕才会发出。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 避免窗口在变动时出现昂贵的计算开销。
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);

1
2
3
4
5
6
7
<div id="watch-example">
<p>
Ask a yes/no question:
<input v-model="question">
</p>
<p>{{ answer }}</p>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<!-- 因为 AJAX 库和通用工具的生态已经相当丰富,Vue 核心代码没有重复 -->
<!-- 提供这些功能以保持精简。这也可以让你自由选择自己更熟悉的工具。 -->
<script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.13.1/lodash.min.js"></script>
<script>
var watchExampleVM = new Vue({
el: '#watch-example',
data: {
question: '',
answer: 'I cannot give you an answer until you ask a question!'
},
watch: {
// 如果 `question` 发生改变,这个函数就会运行
question: function (newQuestion, oldQuestion) {
this.answer = 'Waiting for you to stop typing...'
this.debouncedGetAnswer()
}
},
created: function () {
// `_.debounce` 是一个通过 Lodash 限制操作频率的函数。
// 在这个例子中,我们希望限制访问 yesno.wtf/api 的频率
// AJAX 请求直到用户输入完毕才会发出。想要了解更多关于
// `_.debounce` 函数 (及其近亲 `_.throttle`) 的知识,
// 请参考:https://lodash.com/docs#debounce
this.debouncedGetAnswer = _.debounce(this.getAnswer, 500)
},
methods: {
getAnswer: function () {
if (this.question.indexOf('?') === -1) {
this.answer = 'Questions usually contain a question mark. ;-)'
return
}
this.answer = 'Thinking...'
var vm = this
axios.get('https://yesno.wtf/api')
.then(function (response) {
vm.answer = _.capitalize(response.data.answer)
})
.catch(function (error) {
vm.answer = 'Error! Could not reach the API. ' + error
})
}
}
})
</script>

_.cloneDeep(value) 深拷贝

这个方法类似_.clone,除了它会递归拷贝 value。(注:也叫深拷贝)。

参数

  1. value (*): 要深拷贝的值。

返回

(*): 返回拷贝后的值。

例子

1
2
3
4
5
var objects = [{ 'a': 1 }, { 'b': 2 }];

var deep = _.cloneDeep(objects);
console.log(deep[0] === objects[0]);
// => false

日期

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//y-m-d
getDate() {
const date = new Date();
let year = date.getFullYear();
let month = date.getMonth() + 1;
let day = date.getDate();
month = month.toString().padStart(2, '0')
day = day.toString().padStart(2, '0')
return `${year}-${month}-${day}`;
}
//h-m-s
getTime() {
const date = new Date();
let hour = date.getHours().toString().padStart(2, '0');
let minute = date.getMinutes().toString().padStart(2, '0');
let second = date.getSeconds().toString().padStart(2, '0');
return `${hour}:${minute}:${second}`;
}

判断是否是JSON字符串

1
2
3
4
5
6
7
8
9
10
11
12
isJSONStr(str){
try{
if(JSON.parse(str) instanceof Object){
return true
}
}
catch(error){
console.log(error)
return false
}
}

判断空类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//判断是否是空对象{}
isEmptyObj(obj) {
return obj !== null && typeof obj === 'object' && !Array.isArray(obj)&& (Object.keys(obj).length === 0)
}
//是否是空数组[]
isEmptyArr(Arr){
return Array.isArray(Arr)&&Arr.length===0
}
//是否是空,undefined,null,"",{},[]
isEmpty(value){
if(!value&&value!==0){
return true
}
else{
if(Object.prototype.toString.call(value)==="[object Array]"){
return value.length===0
}
if(Object.prototype.toString.call(value)==="[object Object]"){
return Object.keys(value).length === 0
}
}
return false
}


Lodash工具库
http://www.dwyblog.cn/2023/01/15/Lodash工具库/
作者
幸福来敲门
发布于
2023年1月15日
许可协议