js 实现累加
使用循环实现累加
使用 for 或 while 循环可以轻松实现累加功能。以下是一个示例代码:
function sumWithLoop(arr) {
let total = 0;
for (let i = 0; i < arr.length; i++) {
total += arr[i];
}
return total;
}
const numbers = [1, 2, 3, 4, 5];
console.log(sumWithLoop(numbers)); // 输出 15
使用 reduce 方法实现累加
JavaScript 的数组方法 reduce 是累加操作的理想选择,代码简洁高效:

function sumWithReduce(arr) {
return arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
}
const numbers = [1, 2, 3, 4, 5];
console.log(sumWithReduce(numbers)); // 输出 15
递归实现累加
递归方法也可以实现累加,适用于学习递归的场景:

function sumWithRecursion(arr, index = 0) {
if (index >= arr.length) return 0;
return arr[index] + sumWithRecursion(arr, index + 1);
}
const numbers = [1, 2, 3, 4, 5];
console.log(sumWithRecursion(numbers)); // 输出 15
使用 eval 实现累加(不推荐)
虽然 eval 可以实现累加,但由于安全性和性能问题,不建议在生产环境中使用:
function sumWithEval(arr) {
return eval(arr.join('+'));
}
const numbers = [1, 2, 3, 4, 5];
console.log(sumWithEval(numbers)); // 输出 15
累加对象属性值
如果需要累加对象数组中的某个属性值,可以结合 map 和 reduce:
const items = [
{ value: 10 },
{ value: 20 },
{ value: 30 }
];
const total = items.map(item => item.value).reduce((a, b) => a + b, 0);
console.log(total); // 输出 60






