3

だから私は知っている

variable && runTrue();

本当に意味します

if(variable){
    runTrue();
}

次に、より簡単に書く方法はありますか

if(variable){
    runTrue();
}else{
    runFalse();
}

if-else?の代わりに

4

2 に答える 2

6

条件演算子 を使用した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
}
于 2012-05-31T03:07:36.833 に答える
3

はい、これは通常と同じことをすることがわかりました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-31T02:27:18.223 に答える