您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息

如何同时从左到右将函数应用于数组的两个值?

2024/4/29 20:12:01发布11次查看
使用javascript中的reduce()方法从左到右同时对数组的两个值应用函数,以将其减少为单个值。
以下是参数 -
回调- 对数组中的每个值执行的函数。initialvalue − 用作回调第一次调用的第一个参数的对象。示例您可以尝试运行以下代码来了解如何在 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>
以上就是如何同时从左到右将函数应用于数组的两个值?的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录