underscore.js

2017-10-26  本文已影响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)
}}
}
上一篇下一篇

猜你喜欢

热点阅读