目录

reduce()

描述 (Description)

Javascript数组reduce()方法同时对数组的两个值(从左到右reduce()应用函数,以将其减少为单个值。

语法 (Syntax)

其语法如下 -

array.reduce(callback[, initialValue]);

参数细节 (Parameter Details)

  • callback - 要对数组中的每个值执行的函数。

  • initialValue - 用作第一次调用回调的第一个参数的对象。

返回值 (Return Value)

返回数组的减少的单个值。

兼容性 (Compatibility)

此方法是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;
   };
}

例子 (Example)

请尝试以下示例。

<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>

输出 (Output)

total is : 6
↑回到顶部↑
WIKI教程 @2018