用js数组求和、最大值、最小值、平均值简便写法

作者: admin 日期: 2016-06-03 13:39:49 人气: - 评论: 0
/*平均值:*/  [1,2,3,4,5,6,7,8,9,10].reduce((a,b,c)=>(a*c+b)/(c+1))
/*最大值:*/  [1,2,3,4,5,6,7,8,9,10].reduce((a,b)=>(a>b?a:b))
/*最小值  */  [1,2,3,4,5,6,7,8,9,10].reduce((a,b)=>(a<b?a:b))
/*求和 */     [1,2,3,4,5,6,7,8,9,10].reduce((a,b)=>a+b)

注意:Array的reduce方法需要es5支持,如果浏览器不支持可以使用以下shim

if (typeof Array.prototype.reduce != "function") {
  Array.prototype.reduce = function (callback, initialValue ) {
     var previous = initialValue, k = 0, length = this.length;
     if (typeof initialValue === "undefined") {
        previous = this[0];
        k = 1;
     }
     
    if (typeof callback === "function") {
      for (k; k < length; k++) {
         this.hasOwnProperty(k) && (previous = callback(previous, this[k], k, this));
      }
    }
    return previous;
  };
}


相关内容

发表评论
更多 网友评论0 条评论)
暂无评论

Copyright © 2012-2014 我的代码板 Inc. 保留所有权利。

页面耗时0.0240秒, 内存占用1.82 MB, 访问数据库13次

闽ICP备15009223号-1