だから私は知っている
variable && runTrue();
本当に意味します
if(variable){
runTrue();
}
次に、より簡単に書く方法はありますか
if(variable){
runTrue();
}else{
runFalse();
}
if-else
?の代わりに
だから私は知っている
variable && runTrue();
本当に意味します
if(variable){
runTrue();
}
次に、より簡単に書く方法はありますか
if(variable){
runTrue();
}else{
runFalse();
}
if-else
?の代わりに
条件演算子 を使用した3値式? :
は、このような単純な2値選択のために考案されました。
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();
。