Lodash
cdn 载入
<script src="https://unpkg.com/lodash@4.16.6"></script>
npm 载入
$ npm i -g npm
$ npm i --save lodash
为什么选择 Lodash ?
Lodash 通过降低 array、number、objects、string 等等的使用难度从而让 JavaScript 变得更简单。
Lodash 的模块化方法 非常适用于:
- 遍历 array、object 和 string
- 对值进行操作和检测
- 创建符合功能的函数
以_
符号开头
// 1. Basic for loop. 基本循环
for(var i = 0; i < 5; i++){
//...
}
// 2. Using Array's join and split methods 使用数组的连接和拆分方法
Array.apply(null, Array(5)).forEach(function(){
//...
});
// Lodash
_.times(5, function(){
//...
});
数组拆分:
_.chunk(['a', 'b', 'c', 'd'], 2);
// => [['a', 'b'], ['c', 'd']]
_.chunk(['a', 'b', 'c', 'd'], 3);
// => [['a', 'b', 'c'], ['d']]
_.join
:
_.join(['a', 'b', 'c'], '~');
// => 'a~b~c'