之前计算数组中所有元素求和基本上都是定义初始变量,然后for循环所有元素求和,今天突然发现,数组求和还有专门的方法reduce,,然后看了下对应的api文档,在此记录一下使用心得。
语法
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
参数
| 参数 | 描述 | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| function(total,currentValue, index,arr) | 必需。用于执行每个数组元素的函数。 函数参数:
|
||||||||||
| initialValue | 可选。传递给函数的初始值 |
实例
var numbers = [65, 44, 12, 4];
function getSum(total, num) {
return total + num;
}
function myFunction(item) {
document.getElementById("demo").innerHTML = numbers.reduce(getSum,0);
}
