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
3 Answers
Reset to default 9Javascript 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条)