所以我知道
variable && runTrue();
真正意思
if(variable){
runTrue();
}
那么有没有更简化的写法
if(variable){
runTrue();
}else{
runFalse();
}
而不是if-else
?
所以我知道
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
在大多数情况下都比正常的执行方式更快。
(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();
.