- reduce
- 先去扁平化再求和
- 递归实现
let arr=[1,2,3,4,5,6,7,8,9,10];
let sum = arr.reduce((pre,cur)=>{
return pre+cur;
},0)
console.log(sum);
var arr=[1,2,3,[[4,5],6],7,8,9];
let newArr = arr.toString().split(',').map((item)=>{return Number(item)});
let sum = newArr.reduce((pre,cur)=>{
return pre+cur;
},0)
console.log(sum);
let arr = [1, 2, 3, 4, 5, 6];
function sum(arr) {
if (arr.length === 1) return arr[0];
return arr[0] + sum(arr.splice(1));
}
console.log(sum(arr));