如何同时从左到右对数组的两个值应用函数?
使用reduce()JavaScript中的方法可以从左到右同时对数组的两个值应用函数,以将其缩减为单个值。
以下是参数-
callback- 对数组中的每个值执行的函数。
initialValue- 用作首次调用回调的第一个参数的对象。
示例
您可以尝试运行以下代码来学习如何使用reduce()JavaScript中的方法-
<html>
<head>
<title>JavaScript Array reduce Method</title>
</head>
<body>
<script>
if (!Array.prototype.reduce) {
Array.prototype.reduce = function(fun /*, initial*/) {
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
//如果没有初始值和空数组,则没有值返回
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 (++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>