JavaScript中reduce()方法的使用详解
2015-06-09 00:00
926 查看
JavaScript 数组reduce()方法同时应用一个函数针对数组的两个值(从左到右),以减至一个值。
语法
array.reduce(callback[, initialValue]);
下面是参数的详细信息:
callback : 函数执行在数组中每个值
initialValue : 对象作为第一个参数回调的第一次调用使用
返回值:
返回数组的减少单一个值
兼容性:
这种方法是一个JavaScript扩展到ECMA-262标准; 因此它可能不存在在标准的其他实现。为了使它工作,你需要添加下面的脚本代码的顶部:
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>
这将产生以下结果:
total is : 6
相关文章推荐
- 在JavaScript中处理数组之reverse()方法的使用
- 详解JavaScript中shift()方法的使用
- JavaScript中的some()方法使用详解
- 在Javascript中处理数组之toSource()方法的使用
- JavaScript数组迭代器实例分析
- JavaScript中用sort()方法对数组元素进行排序的操作
- JavaScript实现Iterator模式实例分析
- JavaScript中的splice()方法使用详解
- 简介JavaScript中的unshift()方法的使用
- Javascript监视变量变化的方法
- JavaScript的Date()方法使用详解
- JavaScript中用getDate()方法返回指定日期的教程
- JavaScript中的getDay()方法使用详解
- JavaScript实现函数返回多个值的方法
- JavaScript获取两个数组交集的方法
- JavaScript获取数组最小值和最大值的方法
- JS动态创建DOM元素的方法
- Javascript对象Clone实例分析
- js获取字符串字节数方法小结
- Javascript实现div的toggle效果实例分析