A detailed explanation of the use of the reduce () method in JavaScript

Source: Internet
Author: User
Tags empty javascript extension javascript array

This article mainly introduces the JavaScript in the use of reduce () method, is the basic knowledge of JS introductory learning, need friends can refer to the

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

?

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

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 A. 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 Type   Error (); var i = 0;   if (arguments.length >= 2) {var RV = arguments[1];} else {do {if (i) {RV = this[i++]; 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:

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 The

This will produce the following results:

?

1 Total Is:6

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.