JavaScript 数组Array-reduceRight()方法
时间:2019-08-20 13:50:50 来源:igfitidea点击:
说明
Javascript array reduceRight()方法同时对数组的两个值(从右到左)应用一个函数,以将其缩减为单个值
语法
array.reduceRight(callback[, initialValue]);
参数明细
callback−对数组中的每个值执行的函数。
initialValue−用作回调第一次调用的第一个参数的对象
下面的参数被传递给callback。
previous - 当前索引的值。
value - 当前索引的值。
index - -当前索引。
array - 进行处理的数组
返回值
返回一个带有回调返回值的新数组。
兼容性
此方法是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;
};
}
示例1
var array = [2, 4, 8];
var result = array.reduceRight(function () {
console.log(this);
return true;
});
console.log(result); // true
console.log(array); // [2, 4, 8]
示例2
var arr = [2, 4, 8];
var result = arr.reduceRight(function (previous, value, index, array) {
console.log(previous, value, index, array);
return true;
});
console.log(result); // true
console.log(arr); // [2, 4, 8]
示例3
var array = [2, 4, 8];
var result = array.reduceRight(function (value) {
if (value === 4) {
return false;
}
return true;
});
console.log(result); // true
console.log(array); // [2, 4, 8]

