The use of the reduce () method in JavaScript-basic knowledge

Source: Internet
Author: User
Tags javascript extension javascript array

The JavaScript array reduce () method applies a function to two values (from left to right) of the array at the same time to reduce to a value.
Grammar

Array.reduce (callback[, InitialValue]);

The following are the details of the parameters:

    • Callback: function executes each value in the array
    • InitialValue: The first invocation of an object as the first parameter callback uses the

return value:

Returns the reduction of an array by a single value
Compatibility :

This approach is a JavaScript extension to the ECMA-262 standard; Therefore it may not exist in other implementations of the standard. To make it work, you need to add the top of the following scripting 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 a 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) {
     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)
    RV = Fun.call (null, RV, this[i], I, this);
  }

  return RV;}
 ;
}

Example:

 

This will produce the following results:

Total Is:6

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.