【Lodash源码】_.map() [ map和foreach有什么区别呢?]

本文通过实例对比分析Lodash库中的_.map()和_.forEach()方法,揭示它们在遍历数组时的共同点与不同点。_.forEach()不返回新数组,直接修改原数组;而_.map()返回新数组,保持原数组不变。在源码中,当传入参数为数组时,_.forEach()会调用arrayEach函数进行处理。

我们通过例子来分析源码和两个方法之间的区别

举例:_.forEach()

var array = [1,2,3,4,5];  
var res = _.forEach(array, function (item,index,input) {  
       input[index] = item*10;  
})  
console.log(res);//=>undefined
console.log(array);//=>[10,20,30,40,50]

举例:_.map()

var res = _.map(array, function (item,index,input) {  
       input[index] = item*10;  
})  
console.log(res);//=>[10,20,30,40,50]
console.log(array);//=>[1,2,3,4,5]

共同点:

  1. 都是循环遍历数组中的每一项
  2. 每一次执行匿名函数都支持三个参数,数组中的当前项item,当前项的索引index,原始数组input
  3. 只能遍历数组

不同点:

_.foreach()

没有返回值

对原本数组进行操作

_.map()

有返回值

克隆原本数组 ,再新数组进行操作并返回新数组

?????我在敲黑板

这个同点,请自己在下面的源码中找到原因。

有兴趣交流的朋友,在下面留言

也可加微信群,我们聊聊前端,一起进阶。也可加我微信15956574080

 

 

 

_.map()

/**
 * 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

_.forEach()

注释:forEach()是判断传入的参数是否是数组,对不同类型分别进行不同操作

import arrayEach from './.internal/arrayEach.js'
import baseEach from './.internal/baseEach.js'

/**
 * Iterates over elements of `collection` and invokes `iteratee` for each element.
 * The iteratee is invoked with three arguments: (value, index|key, collection).
 * Iteratee functions may exit iteration early by explicitly returning `false`.
 *
 * **Note:** As with other "Collections" methods, objects with a "length"
 * property are iterated like arrays. To avoid this behavior use `forIn`
 * or `forOwn` for object iteration.
 *
 * @since 0.1.0
 * @alias each
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array|Object} Returns `collection`.
 * @see forEachRight, forIn, forInRight, forOwn, forOwnRight
 * @example
 *
 * forEach([1, 2], value => console.log(value))
 * // => Logs `1` then `2`.
 *
 * forEach({ 'a': 1, 'b': 2 }, (value, key) => console.log(key))
 * // => Logs 'a' then 'b' (iteration order is not guaranteed).
 */
function forEach(collection, iteratee) {
  const func = Array.isArray(collection) ? arrayEach : baseEach
  return func(collection, iteratee)
}

export default forEach

当我们传入数组的时候则会进入arrayEach函数,处理该数组,具体如下:

/**
 * A specialized version of `forEach` for arrays.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns `array`.
 */
function arrayEach(array, iteratee) {
  let index = -1
  const length = array.length

  while (++index < length) {
    if (iteratee(array[index], index, array) === false) {
      break
    }
  }
  return array
}

export default arrayEach

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值