开发者

JavaScript --Example #10 from John Resig`s Learning Advanced JavaScript

Im reading John Resigs "Learning Advanced JavaScript" http://ejohn.org/apps/learn/#10 and came across this function below that I d开发者_开发技巧on`t understand.

The function yell is called with an argument of 4. When this is done, the argument 4 is run through the terniary operator. If it is greater than zero, which it is, then we come to yell(n-1) + a My questions relate to this.

a) does yell(n-1) + a call the function again (i.e. restart it) with an argument of 3.

b) If you do (n-1) + a, you get a result of 3a. Does JavaScript convert 3a to "aaa". I ask this because in the assert line it says yell(4) == "hiyaaaa"

c) after converting it, does it somehow add it to "hiy"? I don`t understand how.

d) if JavaScript does convert 3a to a string of "aaa"s, and somehow manages to add it to "hiy", I don`t understand why yell(4)=hiyaaaa. Yell(n-1) + a = hiyaaa (3as), not hiyaaaa(4"a"s).

As you can see I am totally confused.

function yell(n){
  return n > 0 ? yell(n-1) + "a" : "hiy";
}
assert( yell(4) == "hiyaaaa", "Calling the function by itself comes naturally." );


a) This function is taking advantage of recursion, so yes, the function called again and everything else is pushed on the stack waiting for that return value. b) No, the function is called with a return value as mentioned above. c) See Above. d) It doesn't.

Think of it like this:

function a(val) {
  return val + "a";
}

function b(val) {
  return a(val) + "a";
}

If you call b("hiya") you'll get hiyaaa. Now instead of calling a different function, call the same one.


a) Yes it calls the function again, so the function is recursive.

b) If one of the operands is a string, + does string concatenation.

c) It returns it.

d) Write the recursion out on paper to better visualise it.


For a), it is known as a recursive function, and yes it is calling self with 3.

For b) you aren't just doing (n-1), you are doing yell(n-1) + "a", and once n =0, yell(0) returns 0.

For c), read the last part of b), i.e. because of the ternary statement, it will return "hiy" once n=0.

For d), see the rest of them.


Try replacing the "a" with the argument supplied to the yell function. Like this:

function yell(n){  return n > 0 ? yell(n-1) + n : "hiy"; }
var x = yell(4); log(x);
assert( yell(4) == "hiy1234", "Calling the function by itself comes naturally." );

So, each value of n is taken and put on a LIFO stack ie 4,3,2,1 and when n becomes 0 "hiy" is on top of the LIFO stack. Then the concatenation is done be popping each value off of the stack such that the string becomes "hiy1234".

Hope this helps.

Bumpfster

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜