[英]Short circuit evaluation In javascript
I am in a need to implement short circuit evaluation logic in my code. 我需要在代码中实现短路评估逻辑。 And I read some articles http://en.wikipedia.org/wiki/Short-circuit_evaluation , http://www.grauw.nl/blog/entry/510 to understand about it .
我读过一些文章http://en.wikipedia.org/wiki/Short-circuit_evaluation , http://www.grauw.nl/blog/entry/510了解一下吧。 But they haven't covered in detail and I tried up some examples.
但是他们没有详细介绍,我尝试了一些例子。
Ex: 例如:
function a() {return true;}
function b() {return false;}
function c() {return true;}
Expression 表达
Case 1) a() && b() && c();
情况1)
a() && b() && c();
Case 2) a() || b() && c();
情况2)
a() || b() && c();
a() || b() && c();
Case 3) a() && c() || b();
情况3)
a() && c() || b();
a() && c() || b();
Case 1: 情况1:
c()
will not be executed. c()
将不会执行。
Case 2: 情况2:
b()
and c()
will not be executed b()
和c()
将不会执行
Case 3: 情况3:
b()
will not be executed. b()
将不会执行。
Where should we learn about this short-circuit evaluation? 我们应该从哪里了解这种短路评估?
Where should we learn about this short-circuit evaluation?
我们应该从哪里了解这种短路评估?
The specification is handy, as is MDN . 该规范非常方便, MDN也是如此 。
But the short version is: 但简短的版本是:
The left-hand operand to &&
or ||
&&
或||
的左侧操作数 is always evaluated, giving us the left-hand value . 总是被评估,给我们左手边的值 。
With &&
, if the left-hand value is falsey, the right-hand operand is not evaluated; 使用
&&
,如果左侧值为 falsey,则不评估右侧操作数; the expression's value is the left-hand value. 表达式的值是左侧的值。
With ||
与
||
, if the left-hand value is truthy, the right-hand operand is not evaluated; ,如果左侧值为 true,则不评估右侧操作数;否则为0。 the expression's value is the left-hand value.
表达式的值是左侧的值。
Otherwise, the right-hand operand is evaluated and the expression's result is its value. 否则,将评估右侧操作数,并且表达式的结果为其值。
"Falsey" values are any value that coerces to false
when used as a boolean. “ Falsey”值是用作布尔值时强制转换为
false
任何值。 Those are 0
, ""
, NaN
, undefined
, null
, and of course, false
. 这些是
0
, ""
, NaN
, undefined
, null
,当然还有false
。
"Truthy" values are any values that aren't falsey. “ Truthy”值是任何不虚假的值。
More on my blog: JavaScript's Curiously-Powerful OR Operator ( ||
) . 我的博客上的更多内容: JavaScript的功能强大的OR运算符(
||
) 。 (I keep meaning to do the &&
version of that...) (我的意思是做那个的
&&
版本...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.