JavaScript array.reduceRight()方法对数组的两个值(从右到左)计算的一个函数
reduceRight() - 语法
array.reduceRight(callback[, initialValue]);
callback - 要对数组中的每个值执行的回调函数。
initialValue - 用作回调的第一个调用的第一个参数的对象
reduceRight() - 返回值
返回数组的减少后的右侧单一值。
reduceRight() - 相容性
此方法是ECMA-262标准的JavaScript扩展;因此,它可能不存在于该标准的其他实现中。要使其工作,您需要在脚本顶部添加以下代码。
if (!Array.prototype.reduceRight) { Array.prototype.reduceRight=function(fun /*, initial*/) { var len=this.length; if (typeof fun != "function") throw new TypeError(); //no value to return if no initial value, empty array if (len == 0 && arguments.length == 1) throw new TypeError(); var i=len - 1; 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 < 0) throw new TypeError(); } while (true); } for (; i >= 0; i--) { if (i in this) rv=fun.call(null, rv, this[i], i, this); } return rv; }; }
reduceRight() - 示例
<html> <head> <title>JavaScript Array reduceRight Method</title> </head> <body> <script type="text/javascript"> if (!Array.prototype.reduceRight) { Array.prototype.reduceRight=function(fun /*, initial*/) { var len=this.length; if (typeof fun != "function") throw new TypeError(); //no value to return if no initial value, empty array if (len == 0 && arguments.length == 1) throw new TypeError(); var i=len - 1; 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 < 0) throw new TypeError(); } while (true); } for (; i >= 0; i--) { if (i in this) rv=fun.call(null, rv, this[i], i, this); } return rv; }; } var total=[0, 1, 2, 3].reduceRight(function(a, b) { return a + b; }); document.write("total is : " + total ); </script> </body> </html>
运行上面代码输出
total is : 6