我想用 JavaScript 中的 forEach 数组函数计算总和。 但我没有得到我想要的。
function sum(...args) {
args.forEach(arg => {
var total = 0;
total += arg;
console.log(total);
});
}
sum(1, 3);
如何使用forEach获取总计,或者使用reduce方法?
最佳答案
您最好使用Array#reduce
,因为它就是为了这种目的而制作的。
它需要一个起始值,如果没有给出,它会采用数组的前两个元素,并将数组从字面上减少为单个值。如果数组为空并且未提供起始值,则会抛出错误。
function sum(...args) {
return args.reduce((total, arg) => total + arg, 0);
}
console.log(sum(1, 3));
console.log(sum(1));
console.log(sum());
关于javascript - 用 forEach 函数计算总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52997764/