js实现求和

使用 reduce 方法求和
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // 输出 15
使用 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
使用 for...of 循环求和
const numbers = [1, 2, 3, 4, 5];
let sum = 0;
for (const num of numbers) {
sum += num;
}
console.log(sum); // 输出 15
使用 eval 函数求和(不推荐)
const numbers = [1, 2, 3, 4, 5];
const sum = eval(numbers.join('+'));
console.log(sum); // 输出 15
使用递归方法求和
function sumArray(arr, index = 0) {
if (index === arr.length) return 0;
return arr[index] + sumArray(arr, index + 1);
}
const numbers = [1, 2, 3, 4, 5];
console.log(sumArray(numbers)); // 输出 15
