问题描述
据我了解,逻辑AND&& amp;短路。运算符如下所示:
As far as I understand, short-circuiting with the logical AND && operator works like the following:
假设我有表达式
和 b
然后 a&& b
与相同? b:a
,因为
Assuming I have the expressions a
and b
then a && b
is the same as a ? b : a
since
如果 a
是真实的,那么结果将是 b
和
如果 a
是假的那么结果将是 a
(甚至没有尝试解析 b
)
if a
is truthy then the result will be b
andif a
is falsy then the result will be a
(without even trying to resolve b
)
这就是为什么以下(演示)代码抛出一个SyntaxError:
That being the case why is the following (demo) code throwing a SyntaxError:
var add = function(a,b) {
b && return a+b; // if(b) return a+b
...
}
有没有办法用return语句短路?
Is there a way to short circuit with a return statement?
推荐答案
&&
二元运算符需要两个部分都是表达式。
The &&
binary operator needs both parts to be expressions.
返回
是一个语句而不是一个表达式(它不会产生一个值,因为当函数结束时,一个值就没用了。)
return something
is a statement but not an expression (it doesn't produce a value, as a value wouldn't be useful when the function ends).
只需使用
if (b) return a+b;
带有更易于阅读的代码的附加好处。
with the added benefit of an easier to read code.
阅读更多:
- (EcmaScript规范)
- (MDN)
- Expressions vs Statements
- the return statement (EcmaScript spec)
- logical operators (MDN)
这篇关于带有退货声明的短路的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!