Home > Web Front-end > JS Tutorial > body text

Detailed explanation of the use of reduce() method in JavaScript

高洛峰
Release: 2016-12-28 09:44:47
Original
1374 people have browsed it

The JavaScript array reduce() method applies a function to two values ​​of the array (from left to right) simultaneously to reduce them to one value.
Syntax

array.reduce(callback[, initialValue]);
Copy after login

The following are the details of the parameters:

callback: function is executed on each value in the array

initialValue: object as The first callback of the first parameter callback uses

Return value:

Returns a reduced single value of the array
Compatibility:

This method is a JavaScript extends to the ECMA-262 standard; therefore it may not exist in other implementations of the standard. In order for it to work, you need to add the following script to the top of the code:

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;
 };
}
Copy after login

Example:



JavaScript Array reduce Method




Copy after login

This will produce the following results:

total is : 6
Copy after login

For more detailed explanations of the use of the reduce() method in JavaScript, please pay attention to the PHP Chinese website for related articles!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!