Javascript 中的 reduce()函数

首页 / JavaScript入门教程 / Javascript 中的 reduce()函数

JavaScript array.reduce()方法对数组的两个值(从左到右)计算函数。

reduce() - 语法

array.reduce(callback[, initialValue]);

reduce() - 返回值

返回数组的缩减单值。

reduce() - 相容性

此方法是ECMA-262标准的JavaScript扩展;因此,它可能不存在于该标准的其他实现中。要使其工作,您需要在脚本顶部添加以下代码。

if (!Array.prototype.reduce) {
   Array.prototype.reduce=function(fun /*, initial*/) {
      var len=this.length;
      
      if (typeof fun != "function")
      throw new TypeError();
      
      //no value to return if no initial value and an empty array
      if (len == 0 && arguments.length == 1)
      throw new TypeError();
      
      var i=0;
      if (arguments.length >= 2) {
         var rv=arguments[1];
      } else {
         do {
            if (i in this) {
               rv=this[i++];
               break;
            }
            
            //if array contains no values, no initial value to return
            if (++i >= len)
            throw new TypeError();
         }
         while (true);
      }
      for (; i < len; i++) {
         if (i in this)
         rv=fun.call(null, rv, this[i], i, this);
      }
      return rv;
   };
}

reduce() - 示例

<html>
   <head>
      <title>JavaScript Array reduce Method</title>
   </head>
   
   <body>   
      <script type="text/javascript">
         if (!Array.prototype.reduce) {
            Array.prototype.reduce=function(fun /*, initial*/) {
               var len=this.length;
               
               if (typeof fun != "function")
               throw new TypeError();
               
               //no value to return if no initial value and an empty array
               if (len == 0 && arguments.length == 1)
               throw new TypeError();
               
               var i=0;
               if (arguments.length >= 2) {
                  var rv=arguments[1];
               } else {
                  do {
                     if (i in this) {
                        rv=this[i++];
                        break;
                     }
                     
                     //if array contains no values, no initial value to return
                     if (++i >= len)
                     throw new TypeError();
                  }
                  while (true);
               }
               for (; i < len; i++) {
                  if (i in this)
                  rv=fun.call(null, rv, this[i], i, this);
               }
               return rv;
            };
         }
         var total=[0, 1, 2, 3].reduce(function(a, b){ return a + b; });
         document.write("total is : " + total ); 
      </script>      
   </body>
</html>

运行上面代码输出

total is : 6

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

重学前端 -〔程劭非(winter)〕

Node.js开发实战 -〔杨浩〕

性能工程高手课 -〔庄振运〕

Electron开发实战 -〔邓耀龙〕

正则表达式入门课 -〔涂伟忠〕

Redis核心技术与实战 -〔蒋德钧〕

To B市场品牌实战课 -〔曹林〕

程序员的个人财富课 -〔王喆〕

超级访谈:对话道哥 -〔吴翰清(道哥)〕

好记忆不如烂笔头。留下您的足迹吧 :)