什么是“x&&"foo()"?

2022-01-20 00:00:00 conditional javascript and-operator

我在其他地方看到 某处,

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.

相反,如果 || 语句中的第一个表达式为真,则第二个表达式不会被触及.这样做是因为整个语句已经可以被计算,无论第二个表达式的结果如何,该语句都将返回 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').

相关文章