首頁  >  文章  >  web前端  >  如何同時從右到左對數組的兩個值應用函數?

如何同時從右到左對數組的兩個值應用函數?

WBOY
WBOY轉載
2023-09-16 23:25:081116瀏覽

如何同時從右到左對數組的兩個值應用函數?

使用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刪除