_.maxBy(array, [iteratee=_.identity])

178

_.maxBy(array, [iteratee=_.identity])
_.maxBy类似max方法,计算出一个数组中的最大值,区别是接收一个iteratee遍历器为数组中每一个元素调用根据数组元素值被排列的顺序生成对应的标准值。

参数

array (Array): 需要遍历查找最大值的数组
[iteratee=_.identity] (Function): 对每一个元素都要调用的迭代器

返回值

(*): 返回最大值

例子

var objects = [{ 'n': 1 }, { 'n': 2 }];
 
_.maxBy(objects, function(o) { return o.n; });
// => { 'n': 2 }
 
// The `_.property` iteratee shorthand.
_.maxBy(objects, 'n');
// => { 'n': 2 }

源代码

import isSymbol from './isSymbol.js'

/**
 * This method is like `max` except that it accepts `iteratee` which is
 * invoked for each element in `array` to generate the criterion by which
 * the value is ranked. The iteratee is invoked with one argument: (value).
 *
 * @since 4.0.0
 * @category Math
 * @param {Array} array The array to iterate over.
 * @param {Function} iteratee The iteratee invoked per element.
 * @returns {*} Returns the maximum value.
 * @example
 *
 * const objects = [{ 'n': 1 }, { 'n': 2 }]
 *
 * maxBy(objects, ({ n }) => n)
 * // => { 'n': 2 }
 */
//类似max方法,计算出一个数组中的最大值,区别是接收一个iteratee遍历器为数组中每一个元素调用根据数组元素值被排列的顺序生成对应的标准值。
function maxBy(array, iteratee) {
  let result//结果极值
  if (array == null) {//如果数组为null,返回undefined
    return result
  }
  for (const value of array) {//循环数组
    let computed
    const current = iteratee(value)//iteratee处理后的当前值

    if (current != null && (computed === undefined
          ? (current === current && !isSymbol(current))
          : (current > computed)
        )) {
          //如果current不是null且computed还没有值,并且current不是NaN且不是Symbol对象,就创建computed和result存下当前current
          //否则就比较current和computed的大小
      computed = current
      result = value
    }
  }
  return result//返回找到的极值
}

export default maxBy

注意:此源代码是4.17.4版本,此方法源码有bug,for of 循环中的computed是let声明变量,应放在循环体外面,否则每次循环都会生成新的computed,lodash仓库已在最新master分支修复了此bug

posted @ 2019-04-21 17:01  hahazexia  阅读(1246)  评论(0)    收藏  举报