是<布尔表达式>&&statement() 和 if(<布尔表达式>) statement() 一样吗?
这两个是一样的吗?
假设你有:
var x = true;
然后你有一个:
x && doSomething();
或
if(x) doSomething();
这两种语法有什么不同吗?我是不是偶然发现了一点糖?
Is there any differene whatsoever between the two syntaxes? Did I stumble across a nice bit of sugar?
推荐答案
严格来说,它们会产生相同的结果,但是如果将前一种情况作为其他情况的条件,则会得到不同的结果.这是因为对于 x &&doSomething()
, doSomething()
将返回一个值来表示它的成功.
Strictly speaking, they will produce the same results, but if you use the former case as a condition for something else, you will get dissimilar results. This is because in the case of x && doSomething()
, doSomething()
will return a value to signify its success.
相关文章