underscore.js 分析6 map函數

來源:互聯網
上載者:User

標籤:dex   dash   轉換   bsp   like   過程   迭代   參數   das   

作用:通過轉換函式(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分析中有介紹,不在複述。

 

underscore.js 分析6 map函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.