[英]+ 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: 我正在阅读John Resig的《 JavaScript Ninja的秘密》 ,并且在理解三元运算符如何在此递归函数中工作时遇到了一些麻烦:
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? 我知道它是串联返回的字符串,但是signal(n - 1)
不干扰它呢? 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. +
运算符将-chirp
附加到函数调用的结果 。 signal
is a recursive function - a function that calls itself. signal
是一个递归函数-一个调用自身的函数。
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
子句:
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()
. 因此,实际上,字符串-chirp
与对signal()
的递归调用的结果串联在一起。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.