recursion - Javascript -> how to recursively add an array of numbers? - Stack Overflow

I can't seem to figure out what's wrong with this code -> keeps throwing a "Maximum c

I can't seem to figure out what's wrong with this code -> keeps throwing a "Maximum call stack size exceeded" error.

function arrayIntSum(array) {
    if (array === []){
        return 0;
    }
    else return array.shift() + arrayIntSum(array); 
} 

I can't seem to figure out what's wrong with this code -> keeps throwing a "Maximum call stack size exceeded" error.

function arrayIntSum(array) {
    if (array === []){
        return 0;
    }
    else return array.shift() + arrayIntSum(array); 
} 
Share Improve this question edited Jan 14, 2014 at 20:18 i_made_that asked Jan 14, 2014 at 19:23 i_made_thati_made_that 9471 gold badge8 silver badges19 bronze badges 4
  • Did you event tried debugging, change your if condition before ask here? -1 for lazyness – DontVoteMeDown Commented Jan 14, 2014 at 19:26
  • For informational purposes: array.reduce(function(sum, n) { return sum + n; }, 0); – cookie monster Commented Jan 14, 2014 at 19:30
  • @DontVoteMeDown, can you tell me how I should have approached debugging this problem? I've only been programming for 2 months and sometimes figuring out how to debug is as confusing for me as the algorithm itself. – i_made_that Commented Jan 14, 2014 at 19:42
  • @i_made_that sure! You can learn how to it in Chrome, Firefox or IE. But they're almost the same process between all browsers. – DontVoteMeDown Commented Jan 14, 2014 at 19:45
Add a ment  | 

3 Answers 3

Reset to default 9

Javascript objects are pared by reference.

[] creates a new array instance, which will will never equal your variable.

You want to check the length.

function arrayIntSum(array) {
    if (array.length === 0){
        return 0;
    }
    else return array.shift() + arrayIntSum(array); 
} 

You should check by this way : a.length==0

you pared a with [] , being a '[]' literal, it has different memory space. and a has different memory space. So they are never equal. so recursion cross its limit

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744894200a4599594.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信