[英]Short-circuit for If-else statement
所以我知道
variable && runTrue();
真正意思
if(variable){
runTrue();
}
那么是否有更简化的写作方式
if(variable){
runTrue();
}else{
runFalse();
}
而不是if-else
?
使用条件运算符的三元表达式? :
? :
是为这种简单的二元选择而发明的:
function a() {alert('odd')}
function b() {alert('even')}
var foo = new Date() % 2;
foo? a() : b(); // odd or even, more or less randomly
相当于:
if (foo % 2) {
a(); // foo is odd
} else {
b(); // foo is even
}
是的,我发现这会和普通的if-else
做同样的事情:
(variable) && (runTrue(),1) || runFalse();
它短2个字符(仍然比没有好)并且在jsPerf中测试通常Short-circut evaluation - false
大部分时间的Short-circut evaluation - false
是比正常方式更快。
(variable) && //If variable is true, then execute runTrue and return 1
(runTrue(),1) || // (so that it wouldn't execute runFalse)
runFalse(); //If variable is false, then runFalse will be executed.
但是,当然,你总是可以使用variable?runTrue():runFalse();
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.