JavaScript中reduce()方法的使用詳解
JavaScript 數(shù)組reduce()方法同時應(yīng)用一個函數(shù)針對數(shù)組的兩個值(從左到右),以減至一個值。
語法
array.reduce(callback[, initialValue]);
下面是參數(shù)的詳細信息:
- callback : 函數(shù)執(zhí)行在數(shù)組中每個值
- initialValue : 對象作為第一個參數(shù)回調(diào)的第一次調(diào)用使用
返回值:
返回數(shù)組的減少單一個值
兼容性:
這種方法是一個JavaScript擴展到ECMA-262標準; 因此它可能不存在在標準的其他實現(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)文章
JavaScript Try...Catch 聲明的 使用方法
JavaScript Try...Catch 聲明的 使用方法...2007-04-04
基于JavaScript實現(xiàn)繼承機制之調(diào)用call()與apply()的方法詳解
本文將介紹兩種很類似于對象冒充的繼承方式,即使用call()和apply()方法2013-05-05
Javascript學(xué)習(xí)筆記之 函數(shù)篇(二) : this 的工作機制
與其他編程語言相比,Javascript 對 this 的使用是一套完全不同的機制。this 在五種情況下的值是各有不同的。2014-06-06
服務(wù)端 VBScript 與 JScript 幾個相同特性的寫法 By shawl.qiu
服務(wù)端 VBScript 與 JScript 幾個相同特性的寫法 By shawl.qiu...2007-03-03
深入理解JavaScript系列(30):設(shè)計模式之外觀模式詳解
這篇文章主要介紹了深入理解JavaScript系列(30):設(shè)計模式之外觀模式詳解,外觀模式(Facade)為子系統(tǒng)中的一組接口提供了一個一致的界面,此模塊定義了一個高層接口,這個接口值得這一子系統(tǒng)更加容易使用,需要的朋友可以參考下2015-03-03

