map
_.map(list, iteratee, [context])
Alias: collect
通过对 list 里的每个元素调用转换函数(iteratee 迭代器)生成一个与之相对应的数组。iteratee
传递三个参数:value
,然后是迭代 index
(或 key
注:如果 list 是个 JavaScript 对象是,这个参数就是 key
),最后一个是引用指向整个 list
。
1 2 3 4 5 6
| _.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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import cb from './_cb.js'; import isArrayLike from './_isArrayLike.js'; import keys from './keys.js';
export default function map(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; }
|