博学而笃志 切问而近思 仁在其中
详情
Javascript Array.reduceRight()方法
作者:--     发布时间:2019-11-20     评论:0     阅读:1

javascript数组reduceright()方法同时应用一个函数针对数组的两个值(从右到左),为将其减至一个值。

语法

array.reduceright(callback[, initialvalue]);

下面是参数的详细信息:

  • 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

 



下一篇:测试
相关文章
loading......
最新动态
所有评论

loading......

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册