How to use reduce () in JavaScript
This article mainly introduces how to use the reduce () method in JavaScript. It is the basic knowledge in JS beginners. For more information, see
The reduce () method of the JavaScript array simultaneously applies a function to reduce two values of the array (from left to right) to one value.
Syntax
?
1 |
Array. reduce (callback [, initialValue]); |
The following is the detailed information about the parameters:
Callback: each value of function execution in the array
InitialValue: the object is used as the first call of the first callback parameter.
Return Value:
Returns an array to reduce a single value.
Compatibility:
This method is a JavaScript extension to the ECMA-262 standard; so it may not exist in other implementations of the standard. To make it work, you need to add the top of the following script 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 35 36 37 38 39 40 41 42 43 |
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; }; } |
Example:
?
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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
<Html> <Head> <Title> JavaScript Array reduce Method </title> </Head> <Body> <Script type = "text/javascript"> 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> |
This produces the following results:
?