0

My question is how this function works, what I don't understand is the return part yell(n-1) + "a" what result I expected was 3a but the result was hiyaaaa. I can't figure out how.

Function code

var ninja = { 
  yell: function yell(n){ 
    return n > 0 ? yell(n-1) + "a" : "hiy"; 
  } 
};
ninja.yell(4); //returns hiyaaaa
4

4 回答 4

6

yell(n-1)+"a" calls the function again with a slightly lower value of n, and attaches an a to whatever the recursed call returns. In this case, you get this chain:

ninja.yell(4)
yell(3)+"a"
(yell(2)+"a")+"a"
((yell(1)+"a")+"a")+"a"
(((yell(0)+"a")+"a")+"a")+"a"
((("hiy"+"a")+"a")+"a")+"a"
"hiyaaaa"

Although, personally I'd rewrite the function like so:

ninja = {
    yell: function(n) {return "hiy"+new Array(n+1).join("a");}
};
于 2013-03-30T15:12:04.047 回答
2

yell is a recursive function. When you call it with 4, it calls itself with 3 (4 - 1), which in turn calls itself with 2 (3 - 1), etc., as long as n is > 0.

The reason that yell is available to be called in this way is that the person writing the code wrote a named function expression:

yell: function yell(n){ 
  return n > 0 ? yell(n-1) + "a" : "hiy"; 
} 

What that does is create a function with the name yell, and assign it to the property yell on the object ninja. The property and the function happen to have the same name, but there's no reason they have to, it could have been:

yell: function foo(n){ 
  return n > 0 ? foo(n-1) + "a" : "hiy"; 
} 

yell (the unqualified symbol), or foo in my example above, is in scope within the function because it's the function's name.

It's worth a side-note here that named function expressions don't quite work correctly on IE8 and earlier (although that particular example would still work); more: Double take

于 2013-03-30T15:11:38.657 回答
1
return n > 0 ? yell(n - 1) + "a" : "hiy"; 

yell(n - 1) will be executed before concatenating it with "a". That means as it recurses (and n becomes smaller), it will eventually return "hiy" with the other "a"s concatenated along with it from the previous calls.

于 2013-03-30T15:11:13.997 回答
1

It is recursive function, invoking itself until n==0, works OK.

于 2013-03-30T15:11:19.680 回答