如何從左向右同時對陣列中的兩個值應用函式?


使用 JavaScript 中的 reduce() 方法從左向右同時對陣列中的兩個值應用函式,以將其縮減為一個值。

以下為引數 -

  • callback - 對陣列中每個值執行的函式。
  • initialValue - 用作回撥第一次呼叫的第一個引數的物件。

示例

你可以嘗試執行以下程式碼,瞭解如何在 JavaScript 中使用 reduce() 方法 -

<html>
   <head>
      <title>JavaScript Array reduce Method</title>
   </head>

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

更新於: 23-Jun-2020

152 瀏覽量

開啟您的 事業

完成此課程即可獲得認證

開始
廣告
© . All rights reserved.