位置:首頁 > Web開發 > Javascript教學 > Javascript Array.reduce()方法

Javascript Array.reduce()方法

JavaScript 數組reduce()方法同時應用一個函數針對數組的兩個值(從左到右),以減至一個值。

語法

array.reduce(callback[, initialValue]);

下麵是參數的詳細信息:

  • callback : 函數執行在數組中每個值

  • initialValue : 對象作為第一個參數回調的第一次調用使用

返回值:

返回數組的減少單一個值

兼容性:

這種方法是一個JavaScript擴展到ECMA-262標準; 因此它可能不存在在標準的其他實現。為了使它工作,你需要添加下麵的腳本代碼的頂部:

if (!Array.prototype.reduce)
{
  Array.prototype.reduce = function(fun /*, initial*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    // no value to return if no initial value and an empty array
    if (len == 0 && arguments.length == 1)
      throw new TypeError();

    var i = 0;
    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 >= len)
          throw new TypeError();
      }
      while (true);
    }

    for (; i < len; i++)
    {
      if (i in this)
        rv = fun.call(null, rv, this[i], i, this);
    }

    return rv;
  };
}

例子:

<html>
<head>
<title>JavaScript Array reduce Method</title>
</head>
<body>
<script type="text/javascript">
if (!Array.prototype.reduce)
{
  Array.prototype.reduce = function(fun /*, initial*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    // no value to return if no initial value and an empty array
    if (len == 0 && arguments.length == 1)
      throw new TypeError();

    var i = 0;
    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 >= len)
          throw new TypeError();
      }
      while (true);
    }

    for (; i < len; i++)
    {
      if (i in this)
        rv = fun.call(null, rv, this[i], i, this);
    }

    return rv;
  };
}

var total = [0, 1, 2, 3].reduce(function(a, b){ return a + b; });
document.write("total is : " + total ); 
</script>
</body>
</html>

這將產生以下結果:

total is : 6