欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript中reduce()方法的使用詳解

 更新時(shí)間:2015年06月09日 10:24:46   投稿:goldensun  
這篇文章主要介紹了JavaScript中reduce()方法的使用詳解,是JS入門學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下

 JavaScript 數(shù)組reduce()方法同時(shí)應(yīng)用一個(gè)函數(shù)針對(duì)數(shù)組的兩個(gè)值(從左到右),以減至一個(gè)值。
語(yǔ)法

array.reduce(callback[, initialValue]);

下面是參數(shù)的詳細(xì)信息:

  •     callback : 函數(shù)執(zhí)行在數(shù)組中每個(gè)值
  •     initialValue : 對(duì)象作為第一個(gè)參數(shù)回調(diào)的第一次調(diào)用使用

返回值:

返回?cái)?shù)組的減少單一個(gè)值
兼容性

這種方法是一個(gè)JavaScript擴(kuò)展到ECMA-262標(biāo)準(zhǔn); 因此它可能不存在在標(biāo)準(zhǔn)的其他實(shí)現(xiàn)。為了使它工作,你需要添加下面的腳本代碼的頂部:

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>

這將產(chǎn)生以下結(jié)果:

total is : 6

相關(guān)文章

最新評(píng)論