Please explain usage of _.identity(value) of underscore.js

前端 未结 3 1334
不知归路
不知归路 2021-01-17 08:05

Please explain usage of _.identity(value) of underscore.js. Not able to understand it from the documentation ( http://underscorejs.org/#identity ).

Can

3条回答
  •  春和景丽
    2021-01-17 08:14

    A specific example:

    Underscore.js defines _.each and as like this.

    _.each = function(obj, iterator, context) {
      ...
    }
    

    This iterator shows el value. You maybe have used this idiom.

    _.each([1, 2, 3], function(el){
      console.log(el);
    });
    

    This iterator returns el value without change.

    _.each([1, 2, 3], function(el){
      return el;
    });
    

    The function that returns a value without change occur frequently. So Underscore.js wants to define the function. Underscore.js names the function _.identity.

    _.identity = function(value) {
      return value;
    };
    

    If Underscore.js wants to use a default iterator, all Underscore.js need is call _.identity.

    _.each([1, 2, 3], _.identity);
    

提交回复
热议问题