首页  >  文章  >  web前端  >  如何同时从右到左对数组的两个值应用函数?

如何同时从右到左对数组的两个值应用函数?

WBOY
WBOY转载
2023-09-16 23:25:081117浏览

如何同时从右到左对数组的两个值应用函数?

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

以下是参数:

  • callback − 在数组的每个值上执行的函数。
  • initialValue − 用作回调的第一个参数的对象

示例

您可以尝试运行以下代码,了解如何使用JavaScript中的reduceRight()方法:

<html>
   <head>
      <title>JavaScript Array reduceRight Method</title>
   </head>
   <body>
      <script>
         if (!Array.prototype.reduceRight)
         {
            Array.prototype.reduceRight = function(fun /*, initial*/)
            {
               var len = this.length;
               if (typeof fun != "function")
               throw new TypeError();
             
               // no value to return if no initial value, empty array
               if (len == 0 && arguments.length == 1)
               throw new TypeError();
               var i = len - 1;
               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 < 0)
                     throw new TypeError();
                  }
                  while (true);
                  }
                  for (; i >= 0; i--)
                  {
                     if (i in this)
                     rv = fun.call(null, rv, this[i], i, this);
                  }
               return rv;
            };
         }
         var total = [0, 1, 2, 3].reduceRight(function(a, b) { return a + b; });
         document.write("total is : " + total );
      </script>
   </body>
</html>

以上是如何同时从右到左对数组的两个值应用函数?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除