所以我知道
variable && runTrue();真正意味着
if(variable){
runTrue();
}那么,是否有一种更简化的方式来编写
if(variable){
runTrue();
}else{
runFalse();
}而不是if-else
发布于 2012-05-31 02:27:18
是的,我发现这和正常的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();。
发布于 2012-05-31 03:07:36
使用条件算子 ? :的三元表达式是为这样简单的二进制选择而发明的:
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
}https://stackoverflow.com/questions/10826717
复制相似问题