zoukankan      html  css  js  c++  java
  • underscore.js 分析6 map函数

    作用:通过转换函数(iteratee迭代器)映射列表中的每个值产生价值的新数组。iteratee传递三个参数:value,然后是迭代 index。

    _.map([1, 2, 3], function(num){ return num * 3; });
    => [3, 6, 9]
    _.map({one: 1, two: 2, three: 3}, function(num, key){ return num * 3; });
    => [3, 6, 9]
    _.map([[1, 2], [3, 4]], _.first);
    => [1, 3]

    调用过程:

    1. 

      // Return the results of applying the iteratee to each element.
      _.map = _.collect = function(obj, iteratee, context) {
        iteratee = cb(iteratee, context);
        var keys = !isArrayLike(obj) && _.keys(obj),
            length = (keys || obj).length,
            results = Array(length);
        for (var index = 0; index < length; index++) {
          var currentKey = keys ? keys[index] : index;
          results[index] = iteratee(obj[currentKey], currentKey, obj);
        }
        return results;
      };

    2. cb函数  应该是callback的缩写。

      // An internal function to generate callbacks that can be applied to each
      // element in a collection, returning the desired result — either `identity`,
      // an arbitrary callback, a property matcher, or a property accessor.
      var cb = function(value, context, argCount) {
        if (_.iteratee !== builtinIteratee) return _.iteratee(value, context);
        if (value == null) return _.identity;
        if (_.isFunction(value)) return optimizeCb(value, context, argCount);
        if (_.isObject(value)) return _.matcher(value);
        return _.property(value);
      };

     这里等于又接着调用optimizeCb,关于optimizeCb在_.each分析中有介绍,不在复述。

  • 相关阅读:
    OpenLDAP与Apache
    OpenLDAP双主
    OpenLDAP主从
    LDAP与禅道
    LDAP与jenkins
    LDAP与Samba
    LDAP与SSH
    LDAP客户端
    LDAP与migrationtools 导入系统账号
    OpenLDAP与phpldapadmin的搭建
  • 原文地址:https://www.cnblogs.com/mafeifan/p/5498766.html
Copyright © 2011-2022 走看看