30

20个Lodash 函数瞬间提升代码逼格 - 简书

 4 years ago
source link: https://www.jianshu.com/p/dde83becf100?
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
2019.11.08 22:18:36字数 1,209阅读 397

减少重复操作,提升可读性,提升团队性。

有一大波API将要想你走来

0 _.last(array)

获取array中的最后一个元素 array.length - 1可还行

_.head(array) 获取数组 array 的第一个元素。

1 _.pull(array, [values])

移除数组array中所有和给定值相等的元素

indexOf、splice可还行

var array = [1, 2, 3, 1, 2, 3];
 
_.pull(array, 2, 3);
console.log(array);
// => [1, 1]

_.pullAt 根据索引 indexes,移除array中对应的元素,并返回被移除元素的数组。
_.pullAll 这个方法类似 _.pull,区别是这个方法接收一个要移除值的数组。

3 _.uniq(array)

创建一个去重后的array数组副本。使用了 SameValueZero 做等值比较。只有第一次出现的元素才会被保留。

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

Aarray 系列中还有扁平化、排序、交集、并集、补集等操作

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

原生forEach 不支持对象,不能退出,这些都帮你解决啦。

还有其他高阶函数哦
_.every_.filter_.find_.findLast
_.forEachRight

5 _.keyBy(collection, [iteratee=_.identity])

将数据转化为id可以key值得对象,便于查询,太常用了。

 var list = [{ age: 12, id: 1 }, { age: 14, id: 5 }];
 console.log(_.keyBy(list, (argItem) => argItem.id));
image.png

_.countBy_.groupBy_.orderBy_.sortBy

6 _.shuffle(collection)

打乱一个集合

sort(()=>Math.random()-0.5) 可还行。

_.sample 从collection(集合)中获得一个随机元素。

_.sampleSize 从collection(集合)中获得 n 个随机元素。

下面解释好懂吧

7 _.debounce(func, [wait=0], [options={}])

防抖 setTimeout、clearTimeout可还行。

如果用手指一直按住一个弹簧,它将不会弹起直到你松手为止。

也就是说当调用动作n毫秒后,才会执行该动作,若在这n毫秒内又调用此动作则将重新计算执行时间。

8 _.throttle(func, [wait=0], [options={}])

节流,限制resize这种再好不过了

将水龙头拧紧直到水是以水滴的形式流出,那你会发现每隔一段时间,就会有一滴水流出。

也就是会说预先设定一个执行周期,当调用动作的时刻大于等于执行周期则执行该动作,然后进入下一个新周期。

9 _.defer(func, [args])

推迟调用func,直到当前堆栈清理完毕。 调用时,任何附加的参数会传给func。

_.delay(func, wait, [args]) 延迟 wait 毫秒后调用 func。 调用时,任何附加的参数会传给func。

Function 还有处理参数的、调用次数、柯理化、缓存函数结果等等

10 _.cloneDeep(value)

JSON.parse(JSON.stringfy) 实现深拷贝可还行,还要考虑循环引用问题。

11_.isEqual(value, other)

深度判断两个对象的值是否相等,

_.isEmpty 检查 value 是否为一个空对象,集合,映射或者set。
_.isError 检查 value 是否是 Error
_.isElement 检查 value 是否是可能是 DOM 元素。

12 _.ceil(number, [precision=0])

根据 precision(精度) 向上舍入 number。( precision(精度)可以理解为保留几位小数。)

_.ceil(4.006);
// => 5
 
_.ceil(6.004, 2);
// => 6.01
 
_.ceil(6040, -2);
// => 6100

_.floor(number, [precision=0]) 根据 precision(精度) 向下舍入 number。( precision(精度)可以理解为保留几位小数。)
_.round(number, [precision=0])

13 _.random([lower=0], [upper=1], [floating])

产生一个包括 lower 与 upper 之间的数。 如果只提供一个参数返回一个0到提供数之间的数。 如果 floating 设为 true,或者 lower 或 upper 是浮点数,结果返回浮点数。

_.random(0, 5);
// => an integer between 0 and 5
 
_.random(5);
// => also an integer between 0 and 5
 
_.random(5, true);
// => a floating-point number between 0 and 5
 
_.random(1.2, 5.2);
// => a floating-point number between 1.2 and 5.2

14 _.get(object, path, [defaultValue])

当为了防止后台返回数据存在深层次属性取值失败而导致的渲染问题,再也不用各种? : 、各种||,或是各种assign和扩展运算符了!!!

var object = { 'a': [{ 'b': { 'c': 3 } }] };
 
_.get(object, 'a[0].b.c');
// => 3
 
_.get(object, ['a', '0', 'b', 'c']);
// => 3
 
_.get(object, 'a.b.c', 'default');
// => 'default'

_.set 设置 object对象中对应 path 属性路径上的值,如果path不存在,则创建。 缺少的索引属性会创建为数组,而缺少的属性会创建为对象

15 _.attempt

优雅的写 try catch

尝试调用func,返回结果 或者 捕捉错误对象。任何附加的参数都会在调用时传给func。

// Avoid throwing errors for invalid selectors.
var elements = _.attempt(function(selector) {
  return document.querySelectorAll(selector);
}, '>_>');
 
if (_.isError(elements)) {
  elements = [];
}

16 _.mapKeys(object, [iteratee=_.identity])

_.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
  return key + value;
});
// => { 'a1': 1, 'b2': 2 }

17 _.mapValues(object, [iteratee=_.identity])

var users = {
  'fred':    { 'user': 'fred',    'age': 40 },
  'pebbles': { 'user': 'pebbles', 'age': 1 }
};
 
_.mapValues(users, function(o) { return o.age; });
// => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
 
// The `_.property` iteratee shorthand.
_.mapValues(users, 'age');
// => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)

18 _.escape([string=''])

转义string中的 "&", "<", ">", '"', "'", 和 "`" 字符为HTML实体字符。

_.escapeRegExp([string='']) 转义 RegExp 字符串中特殊的字符 "^", "$", "", ".", "*", "+", "?", "(", ")", "[", "]", "{", "}", 和 "|" in .

19 _.times(n, [iteratee=_.identity])

调用 iteratee n 次,每次调用返回的结果存入到数组中。 iteratee 调用入1个参数: (index)。

_.times(3, String);
// => ['0', '1', '2']
 
 _.times(4, _.constant(0));
// => [0, 0, 0, 0]

20 _.uniqueId([prefix=''])

生成唯一ID。 如果提供了 prefix ,会被添加到ID前缀上。

_.uniqueId('contact_');
// => 'contact_104'
 
_.uniqueId();
// => '105'

至于链式调用,还是少用的好。

在VueCli3.0 中使用Lodash


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK