JavaScript tool library - Lodash.js introduction installation and use

Foreword:

        This article mainly introduces-JavaScript tool library-Lodash.js introduces the installation and use!

        As a newcomer to the workplace, or when you don't have a thorough grasp of many principles of JavaScript, Lodash is definitely a "killer tool". Let's take a look at the power of this "killer tool".

1. Introduction to Lodash

 Lodash is a consistent, modular, high-performance JavaScript utility library .

Lodash is released under the MIT open source license and supports the latest operating environment. Check out the differences between component versions and choose the one that works for you.

 Lodash official website address icon-default.png?t=M3K6https://www.lodashjs.com/

 

2. Why choose Lodash?

  1.   Lodash makes JavaScript easier by reducing the difficulty of using array, number, objects, string, etc. Lodash's modular approach is ideal for :

  • Traverse array, object and string
  • Manipulating and testing values
  • Create a function that conforms to the function

  2. Compatibility

    Tested on Chrome 74-75, Firefox 66-67, IE 11, Edge 18, Safari 11-12, and Node.js 8-12.

3. How to install Lodash?

  1. Browser environment:

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

 

  2. Via npm:

$ npm i -g npm
$ npm i --save lodash

 

  3.  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');

 


                            Friends who see here may be a little confused, let's read down together~~~

 Lodash integrates arrays (Array), collections (Array | Object), functions (Function), language (Clone | Is | To), mathematics (Math), numbers (Random), objects (Object), utility functions, etc. method ....

To put it simply: Lodash can help you use one line of code to implement the sum of a complex object array, one line of code to sort the object array in ascending and descending order, one line of code to achieve a desired anti-shake throttling, and so on. . . .


 

4. What are the common methods of Lodash that are eye-catching?

// 导入 Lodash

import * as _ from "lodash";

  1.  sumBy --- Sum up the specific fields of the array object

        Introduction to the official website

_.sumBy(array, [iteratee=_.identity])

​
// 这个方法类似_.summin 除了它接受 iteratee 来调用 array中的每一个元素,来生成其值排序的标准。 iteratee 会调用1个参数: (value) 。

parameter

  1. array (Array) : The array to iterate over.
  2. [iteratee=_.identity] (Function) : Call the iteration function for each element.

return

     (number) : Return the sum.

example

var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
 
_.sumBy(objects, function(o) { return o.n; });
// => 20
 
// The `_.property` iteratee shorthand.
_.sumBy(objects, 'n');
// => 20

        personal project use

 

  2.  uniq --- deduplicate the array

        Introduction to the official website

_.uniq(array)

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

 parameter

  1. array (Array) : Array to check.

return

     (Array) : Returns the new deduplicated array.

example

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

         personal project use

 

 

  3.  maxBy --- 返回当前数组对象特定 字段 最大值

        Introduction to the official website

_.maxBy(array, [iteratee=_.identity])

// 这个方法类似_.max 除了它接受 iteratee 来调用 array中的每一个元素,来生成其值排序的标准。 iteratee 会调用1个参数: (value) 。

parameter

  1. array (Array) : The array to iterate over.
  2. [iteratee=_.identity] (Function) : Call the iteration function for each element.

return

     (*) : Returns the largest value.

example

var objects = [{ 'n': 1 }, { 'n': 2 }];
 
_.maxBy(objects, function(o) { return o.n; });
// => { 'n': 2 }
 
// The `_.property` iteratee shorthand.
_.maxBy(objects, 'n');
// => { 'n': 2 }

         personal project use

 

 

  4.   orderBy --- Sort the current array object in ascending and descending order according to a specific field

         Introduction to the official website

_.orderBy(collection, [iteratees=[_.identity]], [orders])

// 此方法类似于_.sortBy,除了它允许指定 iteratee(迭代函数)结果如何排序。 如果没指定 orders(排序),所有值以升序排序。 否则,指定为"desc" 降序,或者指定为 "asc" 升序,排序对应值。

 parameter

  1. collection (Array|Object) : The collection to iterate over.
  2. [iteratees=[_.identity]] (Array[]|Function[]|Object[]|string[]) : Iterator function for sorting.
  3. [orders] (string[])iterateesThe sort order of the iterator function.

return

     (Array) : The new sorted array.

example

var users = [
  { 'user': 'fred',   'age': 48 },
  { 'user': 'barney', 'age': 34 },
  { 'user': 'fred',   'age': 40 },
  { 'user': 'barney', 'age': 36 }
];
 
// 以 `user` 升序排序 再  `age` 以降序排序。
_.orderBy(users, ['user', 'age'], ['asc', 'desc']);
// => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]

          personal project use

 

  5.  throttle --- 节流函数

         Introduction to the official website

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

// 创建一个节流函数,在 wait 秒内最多执行 func 一次的函数。 该函数提供一个 cancel 方法取消延迟的函数调用以及 flush 方法立即调用。 可以提供一个 options 对象决定如何调用 func 方法, options.leading 与|或 options.trailing 决定 wait 前后如何触发。 func 会传入最后一次传入的参数给这个函数。 随后调用的函数返回是最后一次 func 调用的结果。

// 注意: 如果 leading 和 trailing 都设定为 true 则 func 允许 trailing 方式调用的条件为: 在 wait 期间多次调用。

// 如果 wait 为 0 并且 leading 为 false, func调用将被推迟到下一个点,类似setTimeout为0的超时。

 parameter

  1. func (Function) : The function to throttle.
  2. [wait=0] (number) : Milliseconds to throttle.
  3. [options=] (Object) : The options object.
  4. [options.leading=true] (boolean) : Specifies to call before throttling begins.
  5. [options.trailing=true] (boolean) : Specifies to call after throttling ends.

return

     (Function) : Returns the throttling function.

example

// 避免在滚动时过分的更新定位
jQuery(window).on('scroll', _.throttle(updatePosition, 100));
 
// 点击后就调用 `renewToken`,但5分钟内超过1次。
var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
jQuery(element).on('click', throttled);
 
// 取消一个 trailing 的节流调用。
jQuery(window).on('popstate', throttled.cancel);

           personal project use

 

 

  6. set , hasetc. some other ES6 syntax

_.set(object, path, value)

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

// Note: 这个方法会改变 object。

 

_.has(object, path)

// 检查 path 是否是object对象的直接属性。

                     Of course, there are many practical methods. If you are interested, you can go to the official website to take a look~~ 

5. Why not completely replace Lodash with ES6?

     Many functions provided by Lodash can already be replaced by ES6, and some Lodash methods are not available in ES6. Libraries like Lodash are also pushing the boundaries of the JavaScript language itself

Guess you like

Origin blog.csdn.net/weixin_56650035/article/details/124508184