Please read the entirety of the question before answering.
I was looking at the you can't do JavaScript under pressure quiz and got to the question about summing values in an array. I wrote the following function (originally without console.log statements) and it wasn't behaving as it should with the input [[1,2,3],4,5] - returning 10 instead of 15. Eventually I figured out how to fix it - add var in front of n and sum. I've been executing this while debugging while in Firefox's Scratchpad, viewing the console output in Firebug.
function arraySum(i) {
// i will be an array, containing integers, strings and/or arrays like itself.
// Sum all the integers you find, anywhere in the nest of arrays.
n=0;
sum=0;
console.log(i.length)
while(n<i.length){
console.log("i["+n+"]="+i[n]);
if(i[n].constructor==Array){
console.log("array n="+n)
sum+=arraySum(i[n]);
console.log("out array n="+n)
}
else if(typeof(i[n])=="number"){
console.log("number")
sum+= i[n];
}
n++;
console.log("sum="+sum+" n="+n)
}
return sum
}
console.log(arraySum([1,[1,2,3],2] ) );
The output is
start
Scratchpad/1 (line 9)
3
Scratchpad/1 (line 17)
i[0]=1
Scratchpad/1 (line 20)
number
Scratchpad/1 (line 28)
sum=1 n=1
Scratchpad/1 (line 33)
i[1]=1,2,3
Scratchpad/1 (line 20)
array n=1
Scratchpad/1 (line 23)
3
Scratchpad/1 (line 17)
i[0]=1
Scratchpad/1 (line 20)
number
Scratchpad/1 (line 28)
sum=1 n=1
Scratchpad/1 (line 33)
i[1]=2
Scratchpad/1 (line 20)
number
Scratchpad/1 (line 28)
sum=3 n=2
Scratchpad/1 (line 33)
i[2]=3
Scratchpad/1 (line 20)
number
Scratchpad/1 (line 28)
sum=6 n=3
Scratchpad/1 (line 33)
out array n=3
Scratchpad/1 (line 25)
sum=7 n=4
Scratchpad/1 (line 33)
7
So eventually I figured out that when the function is recursively called, the outer function's n variable is reset to 0 and modified up to 3, so when it exits, instead of looping one more time (which it would do if n were 2) it leaves the function. This all makes sense until you consider the sum variable, which should be under the same conditions: reset to 0 in the recursive call, then ends up as 6 when it exits the recursive call of the function,
So my question is this:
Why am I getting 7 instead of 6?