如何对包含任意多层嵌套的数组内的所有数字进行求和
多层嵌套数组全量数字求和实现方案
核心思路
不管数组嵌套多少层,本质逻辑都是逐个判断元素类型:
- 若当前元素为数组,继续拆解遍历该元素的所有子项
- 若当前元素为数字,直接累加到总和中
常用语言实现示例
1. JavaScript 实现
极简方案(利用ES6内置API)
直接用flat(Infinity)拍平无限层级数组,再累加:
const arr = [ [1, 2, 3], [ 4, 5, 6, [ [7, 8, 9], 11, 12, 13, [14, 15, [ 16, 17, 18 ] ] ], [19, 20] ] ] const sum = arr.flat(Infinity).reduce((prev, curr) => prev + curr, 0) console.log(sum) // 输出200
递归兼容方案(兼容低版本运行环境)
function calcNestedSum(arr) { let sum = 0 for (const item of arr) { sum += Array.isArray(item) ? calcNestedSum(item) : item } return sum } console.log(calcNestedSum(arr)) // 输出200
迭代方案(避免极深嵌套导致的调用栈溢出)
function calcNestedSumIterate(arr) { let sum = 0 const stack = [...arr] while (stack.length) { const item = stack.pop() if (Array.isArray(item)) { stack.push(...item) } else { sum += item } } return sum }
2. Python 实现
递归实现
def calc_nested_sum(arr): total = 0 for item in arr: total += calc_nested_sum(item) if isinstance(item, list) else item return total arr = [ [1, 2, 3], [ 4, 5, 6, [ [7, 8, 9], 11, 12, 13, [14, 15, [ 16, 17, 18 ] ] ], [19, 20] ] ] print(calc_nested_sum(arr)) # 输出200
迭代实现
def calc_nested_sum_iterate(arr): total = 0 stack = arr.copy() while stack: item = stack.pop() if isinstance(item, list): stack.extend(item) else: total += item return total
内容的提问来源于stack exchange,提问作者LucasBorges-Santos
相关产品推荐
相关产品推荐

