方式1:展平数组再求和
数组扁平化方式有很多,请参照:数据处理 | 数组扁平化(3种)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| function fn(array) { const newArray = array.flat(Infinity); return newArray.reduce((p, c) => p+c, 0); }
const arr = [ 5, 7, [ 4, [2], 8, [1,3], 2 ], [ 9, [] ], 1, 8 ]; console.log(fn(arr));
|
方式2:递归求和
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| function fn(array) { let sum = 0; for (let item of array) { sum += Array.isArray(item) ? fn(item) : item; } return sum; };
const arr = [ 5, 7, [ 4, [2], 8, [1,3], 2 ], [ 9, [] ], 1, 8 ]; console.log(fn(arr));
|
方式3: 同2但用reduce实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| function fn(array) { return array.reduce((acc, cur) => { return acc += Array.isArray(cur) ? fn(cur) : cur; }, 0) }
const arr = [ 5, 7, [ 4, [2], 8, [1,3], 2 ], [ 9, [] ], 1, 8 ]; console.log(fn(arr));
|