標籤: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函數