美文网首页
underscore.js

underscore.js

作者: 千曙 | 来源:发表于2017-10-26 18:33 被阅读14次

    http://underscorejs.org/docs/underscore.html
    源码与我的实现对比:


    function max()

    _.max = function(obj, iteratee, context) {
        var result = -Infinity, lastComputed = -Infinity,
            value, computed;
        if (iteratee == null && obj != null) {
          obj = isArrayLike(obj) ? obj : _.values(obj);
          for (var i = 0, length = obj.length; i < length; i++) {
            value = obj[i];
            if (value > result) {
              result = value;
            }
          }
        } else {
          iteratee = cb(iteratee, context);
          _.each(obj, function(value, index, list) {
            computed = iteratee(value, index, list);
            if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
              result = value;
              lastComputed = computed;
            }
          });
        }
        return result;
      };
    
    imax = function(list, iteratee, context){
        let slist = [];
        let maxCursor = -1;
        let max = Number.NEGATIVE_INFINITY;
      list.forEach(function(n){
        let s = iteratee(n);
        let sn = Number(s);
        if(sn!=NaN){
            slist.push(sn);
        }
      })
      for (var i in slist) {
        if(slist[i]>max){
            max = slist[i];
            maxCursor = i;
        }
      }
      return list[maxCursor]
    }
    

    ie8 forEach 实现

    if(!Array.prototype.forEach){
    Array.prototype.forEach = function(fun){
     var length = this.length;
      for(var i = 0; i<length; i++){
        fun.call(this, this[i], i, this)
    }}
    }
    

    相关文章

      网友评论

          本文标题:underscore.js

          本文链接:https://www.haomeiwen.com/subject/jwcbjxtx.html