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]);
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; }; }
Example:
This will produce the following results:
total is : 6
For more detailed explanations of the use of the reduce() method in JavaScript, please pay attention to the PHP Chinese website for related articles!