The JavaScript Array reduce method iteratively reduces an array to a single value using a callback function from right-to-left.
array.reduceRight(callback [, initialValue])For browsers that don't support the Array reduceRight method, here's an alternative implementation:
/**
* Copyright (c) Mozilla Foundation http://www.mozilla.org/
* This code is available under the terms of the MIT License
*/
if (!Array.prototype.reduceRight) {
Array.prototype.reduceRight = function(fun /*, initial*/) {
var len = this.length >>> 0;
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) {
var 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;
};
}Array ObjectIf you see a typo, want to make a suggestion or have anything in particular you'd like to know more about, please drop us an e-mail at hello at diveintojavascript dot com.
Copyright © 2010-2011 Dive Into JavaScript