Javascript Ternary operator with empty else

后端 未结 7 738
梦如初夏
梦如初夏 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 13:56

    Do this :

    (t==2)?(alert("1")):null;
    

    You could replace null by any expression that has no side effect. () is not a valid expression.

    0 讨论(0)
  • 2020-12-18 13:58

    You putted a lot of useless parentheses, and the best NULL value in js is undefined.

    document.getElementById('btn-ok').onclick = function(){
      var val = document.getElementById('txt-val').value;
      
      val == 2 ? alert(val) : undefined;
    }
    <input id="txt-val" type="number" />
    <button type="button" id="btn-ok">Ok</button>

    using a single line if statement is better though

    if(value === 2) alert(value);
    
    0 讨论(0)
  • 2020-12-18 13:58

    NO, you can't have empty else, better don't use the ternary operator, it requires a third argument. Go with simple if condition.

    if(t==2) alert("2");
    
    0 讨论(0)
  • 2020-12-18 14:00

    Answer to your real question in the comments:

    all2.forEach(function (e) {
        e.getAttribute("class") && only.push(e.getAttribute("class"));
    });
    
    0 讨论(0)
  • 2020-12-18 14:02

    I don't like it's either. So you're on the right track looking for alternatives.

    In this case, I would write:

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

    Your idea is valid too, for instance you can do this:

    t===2 ? alert("2") : null
    

    But it's four extra chars.

    0 讨论(0)
  • 2020-12-18 14:07

    In that case you don't need to use Ternary operator. Ternary operator requires a third argument.

    condition ? expr1 : expr2

    Lokki at Conditional (ternary) Operator

    You can use the if statement

    if ( t == 2 ) alert(1);
    
    0 讨论(0)
提交回复
热议问题