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