代表:我有这个数组
arr=[1,3,7,8];
1st call will result in: [4,8,9]
2nd Call will result in:[12,13]
3rd call will result in:[25]
How to do this using recursion in javascript?
答案 0 :(得分:1)
我不知道你为什么要递归地做,但这是一个可能的解决方案 -
function sum(arr){
// base case
if(arr.length === 1 || arr.length === 0) {
return arr
} else {
return sum(arr.slice(1).map(el => el + arr[0]))
}
}
答案 1 :(得分:1)
您需要考虑3个案例
const foo = ([x,...xs]) => {
if (x === undefined)
return []
else if (xs.length === 0)
return [x]
else
return foo(xs.map(y => x + y))
}
console.log(foo([])) // []
console.log(foo([1])) // [1]
console.log(foo([1,3])) // [4]
console.log(foo([1,3,7])) // [12]
console.log(foo([1,3,7,8])) // [25]

如果您通过编写一些帮助
来区分一些问题,则可以改进该功能
const add = x => y => x + y
const isEmpty = xs => xs.length === 0
const isNull = x => x == null
const foo = ([x,...xs]) => {
if (isNull(x))
return []
else if (isEmpty(xs))
return [x]
else
return foo(xs.map(add(x)))
}
console.log(foo([])) // []
console.log(foo([1])) // [1]
console.log(foo([1,3])) // [4]
console.log(foo([1,3,7])) // [12]
console.log(foo([1,3,7,8])) // [25]