问题描述
我看到说,
x&& foo();
等于
if(x){
foo();
}
我测试过它们确实做了同样的事情。
但为什么呢?究竟是什么 x&& foo()
?
I tested it and they really did the same thing.
But why? What exactly is x && foo()
?
推荐答案
AND和OR运算符都可以快捷方式。
所以&&
只有在第一个表达式为真时才尝试第二个表达式(真相,更多特别)。第二个操作确实填充的事实(无论 foo()
的内容是什么)并不重要,因为它没有执行,除非表示第一个表达式评估一些真实的东西。如果它是真的,那么将执行以尝试第二次测试。
So &&
only tries the second expression if the first is true (truth-like, more specifically). The fact that the second operation does stuff (whatever the contents of foo()
does) doesn't matter because it's not executed unless that first expression evaluates to something truthy. If it is truthy, it then will be executed in order to try the second test.
相反,如果<$中的第一个表达式c $ c> || 声明为真,第二次没有触及。这样做是因为整个语句已经可以被评估,无论第二个表达式的结果如何,语句都将为true,因此它将被忽略并保持不执行状态。
Conversely, if the first expression in an ||
statement is true, the second doesn't get touched. This is done because the whole statement can already be evaluated, the statement will result in true regardless of the outcome of the second expression, so it will be ignored and remain unexecuted.
当使用这样的快捷方式时要注意的情况当然是运营商的情况,其中定义的变量仍然评估为虚假值(例如 0
),以及真实的(例如'零'
)。
The cases to watch out for when using shortcuts like this, of course, are the cases with operators where defined variables still evaluate to falsy values (e.g. 0
), and truthy ones (e.g. 'zero'
).
这篇关于什么是“x&& FOO()" ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!