求和数组为 const arr = [1,2,3,4,5]
- 递归方法
function sum(arr){
if(arr.length === 0){
return 0;
}else if(arr.length === 1){
return arr[0];
}else{
return arr[0]+sum(arr.slice(1));
}
}
- 使用reduce
const sum = arr.reduce((total, curValue) => total + curValue, 0)
- for循环
function sum(arr){
let total = 0;
for(let i = 0; i < arr.length; i+=1){
total = arr[i] + total;
}
return total
}
- forEach/map
function sum(arr){
arr.forEach(item => { // 也可以换成map方法
return item += item;
})
}