_.map(collection, [iteratee=_.identity])

81

_.map(collection, [iteratee=_.identity])
_.map对数组每一个元素执行迭代器后返回由返回值组成的新数组

参数

collection (Array|Object): 需要遍历的集合
[iteratee=_.identity] (Function): 每一次遍历调用的方法

返回值

(Array): 返回新创建的数组

例子

 

function square(n) {
  return n * n;
}
 
_.map([4, 8], square);
// => [16, 64]
 
_.map({ 'a': 4, 'b': 8 }, square);
// => [16, 64] (iteration order is not guaranteed)
 
var users = [
  { 'user': 'barney' },
  { 'user': 'fred' }
];
 
// The `_.property` iteratee shorthand.
_.map(users, 'user');
// => ['barney', 'fred']

 

源代码:

省略iteratee的处理,想看iteratee的处理看这里,https://www.cnblogs.com/hahazexia/p/9901435.html

下面是基础实现,不是最终代码,最终代码也可以循环对象

/**
 * Creates an array of values by running each element of `array` thru `iteratee`.
 * The iteratee is invoked with three arguments: (value, index, array).
 *
 * @since 5.0.0
 * @category Array
 * @param {Array} array The array to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns the new mapped array.
 * @example
 *
 * function square(n) {
 *   return n * n
 * }
 *
 * map([4, 8], square)
 * // => [16, 64]
 */
//对数组每一个元素执行迭代器后返回由返回值组成的新数组
function map(array, iteratee) {
  let index = -1//循环索引
  const length = array == null ? 0 : array.length//数组长度
  const result = new Array(length)//结果数组

  while (++index < length) {//循环调用迭代器,把处理后的返回值存入结果数组
    result[index] = iteratee(array[index], index, array)
  }
  return result
}

export default map

 

posted @ 2018-11-08 17:35  hahazexia  阅读(324)  评论(0)    收藏  举报