为了账号安全,请及时绑定邮箱和手机立即绑定

使用递归在Javascript中对整数数组求和

使用递归在Javascript中对整数数组求和

慕哥6287543 2022-10-21 17:37:10
我是递归新手,想对一个整数数组求和。sumOfInts([1,2,3,4]) //expected output: 10我的尝试:function sumOfInts(array) {  let counter = 0;  let result = 0;  if (counter === array.length - 2) {    return result + array[array.length - 1]  } else {    result += array[counter];    counter++;  }}我尝试了一些方法来让函数在 else 语句中调用自身,但到目前为止都失败了。现在,该函数不返回任何内容。
查看完整描述

4 回答

?
沧海一幻觉

TA贡献1824条经验 获得超5个赞

我对数组进行切片,直到它变空,并用它的第一个元素增加总和值。由于您正在学习递归,我认为此解决方案将帮助您更好地理解递归。但是,考虑到良好的实践和性能,您应该更喜欢reduce。


function sumOfInts(array, sum = 0) {

    if (array.length === 0) return sum;

    return sumOfInts(array.slice(1), sum + array[0]);

}


查看完整回答
反对 回复 2022-10-21
?
繁花如伊

TA贡献2012条经验 获得超12个赞

除非这是一个练习,否则您不需要递归。恕我直言Array#reduce更适合这项任务:


const sum = xs => xs.reduce((tot, x) => tot + x, 0);

sum([1,2,3,4]);

//=> 10

使用递归,您应该利用参数解构和默认值:


const sum = ([x = 0, ...xs]) => xs.length === 0 ? x : x + sum(xs);

sum([1,2,3,4]);

//=> 10


查看完整回答
反对 回复 2022-10-21
?
拉莫斯之舞

TA贡献1820条经验 获得超10个赞

这是一个带有经典函数式编程成分的版本:


const head = ([h]) => h;                                      

const tail = ([, ...t]) => t;                                   

const sumOfInts = (array) =>  array.length == 0 ? 0 : head(array) +                                                          

                                                      sumOfInts(tail(array))                                                                         



sumOfInts([1,2,3,4])

// => 10


查看完整回答
反对 回复 2022-10-21
?
心有法竹

TA贡献1866条经验 获得超5个赞

希望这可以帮助。


function sumOfInts(arr) {

  if (arr.length > 0){

    //Check if length is greater than 0 .

    //If yes then get all the element but not the last

    //And recursively pass the spliced array to the sumOfInts.

    return sumOfInts(arr.splice(0,arr.length - 1)) + arr[0]; 

  }

  return 0;

}

let sum = sumOfInts([1,2,3,4,5]) ;

console.log(sum);


查看完整回答
反对 回复 2022-10-21
  • 4 回答
  • 0 关注
  • 158 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号