简体   繁体   中英

+ operator in a ternary operator

I am reading John Resig's Secrets of the JavaScript Ninja , and I'm having some trouble understanding how the ternary operator works in this recursive function:

var  ninja = {
  chirp: function signal(n) {
    return n > 1 ? signal(n - 1) + '-chirp' : 'chirp';
  }
};

How is the + operator working here? I understand it's concatenating the returned strings, but how is signal(n - 1) not interfering with it? At first glance it would appear it's appending the string to the function call.

The + operator appends -chirp to the result of the function call. signal is a recursive function - a function that calls itself.

With some parenthesis added, it might become clearer to read:

return (n > 1) ? (signal(n - 1) + '-chirp') : ('chirp');

or as a plain if clause:

if( n > 1 ) {
  return signal(n - 1) + '-chirp';
} else {
  return 'chirp';
}

So actually the string -chirp is concatenated with the result of the recursive call to signal() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM