猿问

underscore源码_.max函数写法疑问

underscore源码中求最大值的函数有一处比较使用的是:

if (value != null && value > result)

这里为什么要加多一个value != null的判断~难道还有value为null同时其又还比别的值大的情况?
对应函数源码如下:

_.max = function(obj, iteratee, context) {

    var result = -Infinity,

      lastComputed = -Infinity,

      value, computed;

    if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object') && obj != null) {

      obj = isArrayLike(obj) ? obj : _.values(obj);

      for (var i = 0, length = obj.length; i < length; i++) {

        value = obj[i];

        if (value != null && value > result) {

          result = value;

        }

      }

    } else {

      iteratee = cb(iteratee, context);

      _.each(obj, function(v, index, list) {

        computed = iteratee(v, index, list);

        if (computed > lastComputed || computed === -Infinity && result === -Infinity) {

          result = v;

          lastComputed = computed;

        }

      });

    }

    return result;

  };


慕姐4208626
浏览 470回答 1
1回答

白猪掌柜的

在Chrome的控制台:null&nbsp;>&nbsp;0&nbsp;//&nbsp;falsenull&nbsp;>&nbsp;-1&nbsp;//&nbsp;true
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答