Javascript Array.reduceRight()方法
作者:--
发布时间:2019-11-20
评论:0
阅读:1
javascript数组reduceright()方法同时应用一个函数针对数组的两个值(从右到左),为将其减至一个值。
语法
array.reduceright(callback[, initialvalue]);
下面是参数的详细信息:
返回值:
返回数组reduceright的单一值。
兼容性:
这种方法是一个javascript扩展到ecma-262标准;因此它可能不存在在标准的其他实现。为了使它工作,你需要添加下面的脚本代码的顶部:
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;
};
}
例子:
<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