Javascript Ternary operator with empty else

后端 未结 7 739
梦如初夏
梦如初夏 2020-12-18 13:43

I\'m trying to convert the following if-else to it\'s ternary operator representation in javascript as follows

var x = 2;
if (x === 2) {alert(\"2\");}
else
          


        
相关标签:
7条回答
  • 2020-12-18 14:19

    you have a few options to do this nicely in one line:

    option1 - noop function

    set a global noop function:

    function noop(){}
    (t==2)?(alert("1")):(noop());
    

    option2 - && operator

    when you use && operater, operands are evaluted only if previos ones where true, so you could miply write:

    (t==2) && alert("1");
    

    or, for exapmle if you have an arry you want to push to, you could test it is not null before:

    arr && arr.push(obj)
    
    0 讨论(0)
提交回复
热议问题