+ 1
JavaScript: Using recursion to create countup
https://code.sololearn.com/WnLSAX5PKls7/?ref=app How this code returns [1,2,3,4,5] as output? I analyzed this function as follows, Since n=5; const countArray=countup(5-1); countArray.push(5) return countArray; // [5] n=4, const countArray=countup(4-1); countArray.push(4) return countArray; // [5,4,] n=3, const countArray=countup(3-1); countArray.push(3) return countArray; // [5,4,3] n=2, const countArray=countup(2-1); countArray.push(2) return countArray; // [5,4,3,2] n=1, const countArray=countup(1-1); countArray.push(1) return countArray; // [5,4,3,2,1] Where I went wrong here, How to analyze this code correctly ?
4 Respuestas
+ 1
when constArray=countup(5-1)
it doesnt continue to countArray.push immediately
instead it goes into the countup function, so countup(4-1) will run.
here is the process
n=5
constArray=countup(5-1)
n=4
constArray=countup(4-1)
n=3
constArray=countup(3-1)
n=2
constArray=countup(2-1)
n=1
return []
countArray.push(1)
return countArray
countArray.push(2)
return countArray
countArray.push(3)
return countArray
countArray.push(4)
return countArray
countArray.push(5)
return countArray
0
Taste Thanks a lot .Clear answer
- 1
I hate JavaScript