lodash entry, use. throttle and debounce

Brief introduction

Lodash is a well-known native javascript library, no need to introduce other third-party dependencies. It is intended to improve developer productivity and improve the performance of the original method of birth JS JS library. Simply put, many ways lodash already written for you, a direct call on the line, do not have to think hard to write, but also the consistency of a unified approach. Lodash _ using a simple symbol, like the $ Jquery, like, very simple. There are similar Underscore.js and Lazy.js

Lodash Chinese document  https://www.html.cn/doc/lodash/

stand by

chrome 43 up
Firefox 38 up
IEs 6-11
the MS Edge
Safari upward. 5
(covering almost the most browsers now on the market can be seen)

how to install

Browser

<script src="lodash.js"></script> Direct introduction of download, or use cdn

NPM
$ Above sea level - g above sea level
$ npm i --save lodash

 

First global installed, installed separately to the project

node.js

var _ = require('lodash');

 

Why lodash

By using an array, numbers, objects, strings or the like, Lodash JavaScript, easier.

Common lodash function

(Reference Version lodash v4.16.1)

1, N cycles
<Script type = " text / JavaScript " > 
    the console.log ( ' ------- ------- JavaScript ' );
     // JS native cyclic process 
    for ( var I = 0 ; I < . 5 ; I ++ ) {
        console.log(i);
    }
    console.log('------- lodash -------');
    //ladash的times方法
    _.times(5,function(a){
        console.log(a);
    });
</script>

forStatement is the choice for execution of the loop, but in the use of the code above scenario, _.times()solution is more concise and easy to understand.

2, deep to find the attribute values
<script type="text/javascript">
    var ownerArr = [{
        "owner": "Colin",
        "pets": [{"name": "dog1"}, {"name": "dog2"}]
    }, {
        "owner": "John",
        "pets": [{"name": "dog3"}, {"name": "dog4"}]
    }];
    var jsMap = ownerArr.map(function (owner) {
        return owner.pets[0].name;
    });
    console.log('------- jsMap -------');
    console.log(jsMap);

    var lodashMap = _.map(ownerArr, 'pets[0].name');
    Kansolklog ( " ------- ------- Lodshanap ' );
    Kansolklog (Lodshanap);
</script>

 

 

Lodash in _.mapan array of methods and JavaScript natively is very like, but it still has a very useful upgrade. You can browse deeply nested object property by a string instead of the callback function.

 

3, deep clone
<script type="text/javascript">
    var objA = {
        "name": "戈德斯文"
    };
    var objB = _.cloneDeep (KEY);
    console.log (KEY);
    console.log(objB);
    console.log(objA === objB);
</script>

 

 

Depth clone JavaScript objects is difficult, and there is no simple solution. You can use the native solution: JSON.parse(JSON.stringify(objectToClone)) the depth of cloning . However, this solution is viable only when the internal object does not approach.

 

4, obtaining a random value within a specified range
<script type="text/javascript">
    function getRandomNumber(min, max){
        return Math.floor(Math.random() * (max - min)) + min;
    }
    console.log (getRandomNumber ( 15 , 20 ));

    console.log(_.random(15, 20));

</script>

Lodash the  _.random native methods than the above and more powerful and flexible. You can only pass a parameter as maximum, you can also specify the results returned to the floating point_.random(15,20,true)

5, extended object
<Script type = " text / JavaScript " > 
    Object.prototype.extend = function (obj) {
         for ( var I in obj) {
             IF (obj.hasOwnProperty (I)) {     // determines there is an extended object attribute, 
                the this [I] = obj [I];
            }
        }
    };

    var objA = {"name": "戈德斯文", "car": "宝马"};
    var objB = {"name": "柴硕", "loveEat": true};

    objA.extend (objB);
    console.log (KEY); 

    console.log(_.assign(objA, objB));
</script>

_.assign The method of receiving a plurality of parameters may be extended objects are combined to the back of the object

 

6 random from the list, select list items
<Script type = " text / JavaScript " >
     var SmartTeam = [ " de gentle " , " Hai month " , " wood master " , " division Babe " ];

    function randomSmarter(smartTeam){
        var index = Math.floor(Math.random() * smartTeam.length);
        return smartTeam[index];
    }

    console.log(randomSmarter(smartTeam));

    // Lodash
    console.log(_.sample(smartTeam));
    console.log(_.sampleSize(smartTeam,2));
</script>

 

 

Furthermore, you can specify the number of returned random elements _.sampleSize(smartTeam,n), n-number of elements need to return to

 

7, determines whether the object contains an element
<script type="text/javascript">
    var smartPerson = {
            'name': '戈德斯文',
            'gender': 'male'
        },
        SmartTeam = [ " Gode gentle " , " Hai month " , " wood master " , " division Babe " ];


    the console.log (. _ Includes (smartPerson, ' de gentle ' ));
    the console.log (. _ Includes (SmartTeam, ' Hai month ' ));
    console.log(_.includes(smartTeam, '杨海月',2));
</script>

_.includes()The first parameter is the object to be queried, the second argument is the element to be queried, the third parameter is the beginning of the query index

 

8, traversal cycle

 

<script type="text/javascript">
    _([1, 2]).forEach(function(value) {
        console.log(value);
    });
    _.forEach([1, 3] , function(value, key) {
        console.log(key,value);
    });
</script>

Both methods outputs '1' and '2', not only the array, the object may be, after the array keyis the index of the element, when the object is passed in time, keyis the attribute, valuethe value

 

9, through the loop to execute a method

_.map()

<script type="text/javascript">
    function square(n) {
        return n * n;
    }

    console.log(_.map([4, 8], square));
    // => [16, 64]

    console.log(_.map({ 'a': 4, 'b': 8 }, square));
    // => [16, 64] (iteration order is not guaranteed)

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

    // The `_.property` iteratee shorthand.
    console.log(_.map(users, 'user'));
    // => ['barney', 'fred']
</script>

 

 

10, test value is empty

_.isEmpty()

<script type="text/javascript">
    _.isEmpty(null);
    // => true

    _.isEmpty(true);
    // => true

    _.isEmpty(1);
    // => true

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

    _.isEmpty({ 'a': 1 });
    // => false
</script>

 

 

11, look for properties

_.find()_.filter()_.reject()

<script type="text/javascript">
    var users = [
        {'user': 'barney', 'age': 36, 'active': true},
        {'user': 'fred', 'age': 40, 'active': false},
        {'user': 'pebbles', 'age': 1, 'active': true}
    ];

    console.log(_.find(users, function (o) {
        return o.age < 40;
    }));
    console.log(_.find(users, {'age': 1, 'active': true}));
    console.log(_.filter(users, {'age': 1, 'active': true}));
    console.log(_.find(users, ['active', false]));
    console.log(_.filter(users, ['active', false]));
    console.log(_.find(users, 'active'));
    console.log(_.filter(users, 'active'));

</script>

 

 

_.find()The first element of the first return true value. _.filter()Returns an array of all the elements of true value. _.reject()A _.filterreverse method, does not return a true value (set) element

 

 

12, deduplication array

_.uniq(array)Create an array of de-duplicated copy of the array.

Parameters  array (Array): To check the array.

After the return of an array of new deduplication

<script type="text/javascript">
    var arr1 = [2, 1, 2];

    was Arr2 = _.uniq (arr1);


    function unique(arr) {
        var newArr = [];
        for (var i = 0; i < arr.length; i++) {
            if(newArr.indexOf(arr[i]) == -1){
                newArr.push(arr[i]);
            }
        }
        return newArr;
    }

    console.log(arr1);
    console.log(arr2);
    console.log(unique(arr1));
</script>

 

 

 

 

_.uniqBy(array,[iteratee=_.identity]) This method is similar  _.uniq , except that it accepts a  iteratee (iterated function), each element of each array invocation (Array) to generate a unique standard calculations. iteratee will pass a parameter when you call: (value).


<script type="text/javascript">
    console.log(_.uniqBy([2.1, 1.2, 2.3], Math.floor));
    // => [2.1, 1.2]
    
    console.log(_.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'));
    // => [{ 'x': 1 }, { 'x': 2 }]
</script>

 

Math.floor Simply rounded down, de-duplication, and not change the original array, it is 2.1 and 1.2, 1 and 2 are not.
 
 
13, inserted into the template

_.template([string=''], [options={}])

 

<div id="container"></div>

<script src="https://cdn.bootcss.com/lodash.js/4.17.4/lodash.min.js"></script>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        var Data = [{name: ' de Sven ' }, {name: ' Cai master ' }, {name: ' Hai months ' }];
         var T = _.template ($ ( " #tpl " ) .html () );
        $("#container").html(t(data));
    });
</script>
<script type="text/template" id="tpl">
    <% _.each(obj,function(e,i){ %>
        <ul>
            <li><%= e.name %><%= i %></li>
        </ul>
    <%})%>
</script>

 

 

 

 

14、

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

 

Create a throttling function, a function of performing up to func in wait seconds. This function provides a cancel method to cancel the delayed function call and flush method is called immediately. Options object can provide a method to determine how to call func, options.leading and | or options.trailing decide how to wait before and after the trigger. func will be passed in the last argument passed to this function. Then call the function returns the result of the last func call.

Note: If the leading and trailing both set to true then invoke the func allow trailing conditions: multiple calls during the wait.

If the wait is 0 and is leading to false , FUNC call will be postponed to the next point, similar setTimeout timeout 0.

 

 

View  David Corbacho's article  to understand  _.throttle the  _.debounce difference.

parameter

  1. func (Function) : function to be throttled.
  2. [wait=0] (Number) : ms require throttling.
  3. [options={}] (Object) : Object option.
  4. [options.leading=true] (boolean) : Specifies the call before the start of the throttle.
  5. [options.trailing=true] (boolean) : Specifies the call at the end of the throttle.

example

// to avoid excessive update scroll positioning 
the jQuery (window) .on ( ' Scroll ' , _.throttle (updatePosition, 100 ));
 
// Click after the call `renewToken`, but within five minutes more than once. 
var Throttled = _.throttle (renewToken, 300000 , { ' trailing ' : to false });
jQuery(element).on('click', throttled);
 
// cancel a trailing throttle call of. 
the jQuery (window) .on ( ' the popstate ' , throttled.cancel);

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 



Guess you like

Origin www.cnblogs.com/yuanjili666/p/12170683.html