
使用JavaScript中的reduce()方法从左到右同时对数组的两个值应用函数,以将其减少为单个值。
以下是参数 -
您可以尝试运行以下代码来了解如何在 JavaScript 中使用 reduce() 方法 -
<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();
// 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>以上就是如何同时从左到右将函数应用于数组的两个值?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号