How do you use the ? : (conditional) operator in JavaScript?

前端 未结 18 1672
感动是毒
感动是毒 2020-11-21 05:48

In simple words, what is the ?: (conditional, "ternary") operator and how can I use it?

18条回答
  •  梦谈多话
    2020-11-21 06:13

    It's an if statement all on one line.

    So

    var x=1;
    (x == 1) ? y="true" : y="false";
    alert(y);
    

    The expression to be evaluated is in the ( )

    If it matches true, execute the code after the ?

    If it matches false, execute the code after the :

提交回复
热议问题