Home  >  Article  >  Web Front-end  >  How to apply a function to two values ​​of an array simultaneously from left to right?

How to apply a function to two values ​​of an array simultaneously from left to right?

王林
王林forward
2023-08-29 14:37:09663browse

How to apply a function to two values ​​of an array simultaneously from left to right?

Apply a function to two values ​​of an array simultaneously from left to right using the reduce() method in JavaScript to reduce them to a single value.

The following are the parameters -

  • Callback- The function that is executed for each value in the array.
  • initialValue − The object used as the first parameter for the first callback call.

Example

You can try running the following code to learn how to use the reduce() method in JavaScript -

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

The above is the detailed content of How to apply a function to two values ​​of an array simultaneously from left to right?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete