js实现求和
实现 JavaScript 求和的方法
使用 reduce 方法对数组求和
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // 输出 15
reduce 方法通过遍历数组累加元素,初始值设为 0 确保空数组也能正确返回 0。
使用 for 循环遍历求和
const numbers = [1, 2, 3, 4, 5];
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
console.log(sum); // 输出 15
传统循环方式,适用于需要中断循环或复杂逻辑的场景。

使用 eval 动态计算字符串表达式(不推荐)
const numbers = [1, 2, 3, 4, 5];
const sum = eval(numbers.join('+'));
console.log(sum); // 输出 15
将数组转为 1+2+3+4+5 字符串后通过 eval 执行,存在安全风险,仅作演示。

递归求和
function sumArray(arr, index = 0) {
return index >= arr.length ? 0 : arr[index] + sumArray(arr, index + 1);
}
console.log(sumArray([1, 2, 3, 4, 5])); // 输出 15
递归实现,需注意栈溢出风险,适合学习算法场景。
使用 arguments 对象对函数参数求和
function sum() {
return [...arguments].reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3, 4, 5)); // 输出 15
适用于不确定参数数量的场景,通过展开运算符转为数组处理。
注意事项
- 浮点数求和时建议使用
toFixed处理精度问题:const floatSum = [0.1, 0.2].reduce((a, b) => (a + b).toFixed(1)); console.log(floatSum); // 输出 "0.3" - 大数组求和时优先考虑循环而非递归,避免堆栈溢出。






