您的位置:首页 > Web前端 > JavaScript

高性能的JavaScript库---Lodash

2016-05-13 17:35 507 查看
上周在仿做Nodejs社区的时候,遇到了lodash这个javascript库,很惭愧,那也是我第一次听说lodash。人嘛,对于新鲜的事物总是会或多或少感到些好奇的,于是就毫不犹豫地去lodash官网逛了逛......咦...这货我怎么感觉在哪儿见过?......额,尼玛这不就是underscore吗?难道是升级版?于是接着各种百度,google......先在这里简单总结一下吧!

lodash中文网上的第一句话是这么说的:

这是一个具有一致接口、模块化、高性能等特性的 JavaScript 工具库。

字体好大,先不管了。

说到模块化,其实这也是lodash的一大亮点,也就是说开发者可以按需加载,而不是引用整个库。每一个模块都暴露在了npm中,可以单独引入进来:



npm install lodash.map

var map = require('lodash.map');


lodash和underscore都是现在非常流行的两个javascript库,提供了一套函数式编程的实用功能。而lodash本身最初也是underscore的一个fork,因为和其他(Underscore.js的)贡献者意见相左。lodash主要使用了延迟计算,所以也使得lodash的性能远远超过了Underscore。在lodash中使用延迟计算,也就意味着当我们使用链式方法时,在直接或间接调用value()之前是不会执行的。下面先简单介绍一些我用到过的或者印象比较深刻的方法吧,更多方法请自行查看lodash官方文档

演示:

1)
_.map(collection, [iteratee=_.identity], [thisArg])


作用:创建一个经过
iteratee
处理的集合中每一个元素的结果数组. iteratee 会传入3个参数:(value, index|key, collection).

别名(Aliases):_.collect

参数1): 需要遍历的集合,可以是数组,对象或者字符串.

参数2): 迭代器,可以是函数,对象或者字符串.

参数3): 迭代器中this所绑定的对象.

返回值(Array): 映射后的新数组.

示例:

function timesThree(n) {
return n * 3;
}

_.map([1, 2], timesThree);
// => [3, 6]

_.map({ 'a': 1, 'b': 2 }, timesThree);
// => [3, 6] (iteration order is not guaranteed)

var users = [
{ 'user': 'barney' },
{ 'user': 'fred' }
];

// using the `_.property` callback shorthand
_.map(users, 'user');
// => ['barney', 'fred']


2)
_.chunk(array, [size=1])


作用:将
array
拆分成多个
size
长度的块,把这些块组成一个新数组。 如果
array
无法被分割成全部等长的块,那么最后剩余的元素将组成一个块.

参数1): 需要被处理的数组.

参数2): 每个块的长度.

返回值(Array): 返回一个包含拆分块数组的新数组(相当于一个二维数组).

示例:

_.chunk(['a', 'b', 'c', 'd'], 2);
// => [['a', 'b'], ['c', 'd']]

_.chunk(['a', 'b', 'c', 'd'], 3);
// => [['a', 'b', 'c'], ['d']]


3)
_.compact(array)


作用:创建一个新数组并包含原数组中所有的非假值元素。例如
false
null
0
""
undefined
NaN
都是“假值”.

参数: 需要被过滤的数组.

返回值(Array): 过滤假值后的数组.

示例:

_.compact([0, 1, false, 2, '', 3]);
// => [1, 2, 3]


4)
_.difference(array, [values])


作用:创建一个差异化后的数组,不包括使用
SameValueZero
方法提供的数组.

参数1): 需要处理的数组.

参数2): 数组需要排除掉的值.

返回值(Array): 过滤后的数组.

示例:

_.difference([1, 2, 3], [4, 2]);
// => [1, 3]
_.difference([1, '2', 3], [4, 2]);
// => [1, "2", 3]


5)
_.drop(array, [n=1])


作用:将
array
中的前
n
个元素去掉,然后返回剩余的部分.

参数1): 被操作的数组.

参数2): 去掉的元素个数.

返回值(Array): 数组的剩余部分.

示例:

_.drop([1, 2, 3]);
// => [2, 3] 默认是1开始的

_.drop([1, 2, 3], 2);
// => [3]

_.drop([1, 2, 3], 5);
// => []

_.drop([1, 2, 3], 0);
// => [1, 2, 3]


6)
_.dropRight(array, [n=1])


作用:将
array
尾部的
n
个元素去除,并返回剩余的部分.

参数1): 需要被处理的数组.

参数2): 去掉的元素个数.

返回值(Array): 数组的剩余部分.

示例:

_.dropRight([1, 2, 3]);
// => [1, 2]

_.dropRight([1, 2, 3], 2);
// => [1]

_.dropRight([1, 2, 3], 5);
// => []

_.dropRight([1, 2, 3], 0);
// => [1, 2, 3]


7)
_.dropRightWhile(array, [predicate=_.identity], [thisArg])


作用:从尾端查询(右数)数组
array
,第一个不满足
predicate
条件的元素开始截取数组.

参数1): 需要查询的数组.

参数2): 迭代器,可以是函数,对象或者字符串.

参数3): 对应
predicate
属性的值.

返回值(Array): 截取元素后的数组.

示例:

_.dropRightWhile([1, 2, 3], function(n) {
return n > 1;
});
// => [1]

var users = [
{ 'user': 'barney',  'active': true },
{ 'user': 'fred',    'active': false },
{ 'user': 'pebbles', 'active': false }
];

// using the `_.matches` callback shorthand
_.pluck(_.dropRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');
// => ['barney', 'fred']

// using the `_.matchesProperty` callback shorthand
_.pluck(_.dropRightWhile(users, 'active', false), 'user');
// => ['barney']

// using the `_.property` callback shorthand
_.pluck(_.dropRightWhile(users, 'active'), 'user');
// => ['barney', 'fred', 'pebbles']


8)
_.pluck(collection, path)


作用:抽取集合中path所指定的路径的属性值.

参数1): 需要抽取的数组.

参数2): 需要抽取的属性所对应的路径.

返回值(Array): 抽取的属性值所组成的数组.

示例:

var users = [
{ 'user': 'barney', 'age': 36 },
{ 'user': 'fred',   'age': 40 }
];

_.pluck(users, 'user');
// => ['barney', 'fred']

var userIndex = _.indexBy(users, 'user');
_.pluck(userIndex, 'age');
// => [36, 40] (iteration order is not guaranteed)


9)
_.fill(array, value, [start=0], [end=array.length])


作用:使用
value
值来填充(也就是替换)
array
,从
start
位置开始, 到
end
位置结束(但不包含end位置).

参数1): 需要填充的数组.

参数2): 填充
array
元素的值.

参数3): 起始位置(包含).

参数4): 结束位置(不含).

返回值(Array): 填充后的数组.

示例:

var array = [1, 2, 3];

_.fill(array, 'a');
console.log(array);
// => ['a', 'a', 'a']

_.fill(Array(3), 2);
// => [2, 2, 2]

_.fill([4, 6, 8], '*', 1, 2);
// => [4, '*', 8]


10)
_.findIndex(array, [predicate=_.identity], [thisArg])


作用:该方法类似
_.find
,区别是该方法返回的是符合
predicate
条件的第一个元素的索引,而不是返回元素本身.

参数1): 需要搜索的数组.

参数2): 迭代器,可以是函数,对象或者字符串.

参数3): 对应
predicate
属性的值.

返回值(Number): 符合查询条件的元素的索引值, 未找到则返回
-1
.

示例:

var users = [
{ 'user': 'barney',  'active': false },
{ 'user': 'fred',    'active': false },
{ 'user': 'pebbles', 'active': true }
];

_.findIndex(users, function(chr) {
return chr.user == 'barney';
});
// => 0

// using the `_.matches` callback shorthand
_.findIndex(users, { 'user': 'fred', 'active': false });
// => 1

// using the `_.matchesProperty` callback shorthand
_.findIndex(users, 'active', false);
// => 0

// using the `_.property` callback shorthand
_.findIndex(users, 'active');
// => 2


11)
_.find(collection, [predicate=_.identity], [thisArg])


作用:遍历集合中的元素,返回最先经
predicate
检查为真值的元素. predicate 会传入3个元素:(value, index|key, collection).

参数1): 要检索的集合,可以是数组,对象或者字符串.

参数2): 迭代器,可以是函数,对象或者字符串.

参数3): 迭代器中this所绑定的对象.

返回值: 匹配元素,否则返回
undefined.


示例:

var users = [
{ 'user': 'barney',  'age': 36, 'active': true },
{ 'user': 'fred',    'age': 40, 'active': false },
{ 'user': 'pebbles', 'age': 1,  'active': true }
];

_.find(users, function(o) { return o.age < 40; });
// =>  'barney'

// 使用了 `_.matches` 的回调结果
_.find(users, { 'age': 1, 'active': true });
// =>  'pebbles'

// 使用了 `_.matchesProperty` 的回调结果
_.find(users, ['active', false]);
// =>  'fred'

// 使用了 `_.property` 的回调结果
_.find(users, 'active');
// =>  'barney'


12)
_.forEach(collection, [iteratee=_.identity], [thisArg])


作用:调用 iteratee 遍历集合中的元素, iteratee 会传入3个参数:(value, index|key, collection)。 如果显式的返回 false ,iteratee 会提前退出.

参数1): 需要遍历的集合,可以是数组,对象或者字符串.

参数2): 迭代器,只能是函数.

参数3): 迭代器中this所绑定的对象.

返回值: 遍历后的集合.

示例:

_([1, 2]).forEach(function(value) {
console.log(value);
});
// => 输出 `1` 和 `2`

_.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
console.log(key);
});
// => 输出 'a' 和 'b' (不保证遍历的顺序)


13)_.reduce(collection, [iteratee=_.identity], [accumulator], [thisArg])

作用:通过 iteratee 遍历集合中的每个元素. 每次返回的值会作为下一次 iteratee 使用。如果没有提供accumulator,则集合中的第一个元素作为 accumulator. iteratee 会传入4个参数:(accumulator, value, index|key, collection).

参数1): 需要遍历的集合,可以是数组,对象或者字符串.

参数2): 迭代器,只能是函数.

参数3): 累加器的初始化值.

参数4): 迭代器中this所绑定的对象.

返回值: 累加后的值.

示例:

_.reduce([1, 2], function(total, n) {
return total + n;
});
// => 3

_.reduce({ 'a': 1, 'b': 2 }, function(result, n, key) {
result[key] = n * 3;
return result;
}, {});
// => { 'a': 3, 'b': 6 } (iteration order is not guaranteed)


14)_.some(collection, [predicate=_.identity], [thisArg])

作用:通过 predicate 检查集合中的元素是否存在任意真值的元素,只要 predicate 返回一次真值,遍历就停止,并返回 true. predicate 会传入3个参数:(value, index|key, collection).

参数1): 需要遍历的集合,可以是数组,对象或者字符串.

参数2): 迭代器,可以是函数,对象或字符串.

参数3): 迭代器中this所绑定的对象.

返回值: 如果任意元素经 predicate 检查都为真值,则返回true,否则返回 false.

示例:

_.some([null, 0, 'yes', false], Boolean);
// => true

var users = [
{ 'user': 'barney', 'active': true },
{ 'user': 'fred',   'active': false }
];

// using the `_.matches` callback shorthand
_.some(users, { 'user': 'barney', 'active': false });
// => false

// using the `_.matchesProperty` callback shorthand
_.some(users, 'active', false);
// => true

// using the `_.property` callback shorthand
_.some(users, 'active');
// => true


15)_.chain(value)

作用:创建一个包含 value 的 lodash 对象以开启内置的方法链.方法链对返回数组、集合或函数的方法产生作用,并且方法可以被链式调用.

参数: 需要被包裹成lodash对象的值.

返回值: 新的lodash对象的实例.

示例:

var users = [
{ 'user': 'barney',  'age': 36 },
{ 'user': 'fred',    'age': 40 },
{ 'user': 'pebbles', 'age': 1 }
];

var youngest = _.chain(users)
.sortBy('age')
.map(function(chr) {
return chr.user + ' is ' + chr.age;
})
.first()
.value();
// => 'pebbles is 1'
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: