What is “?:” notation in JavaScript?

后端 未结 4 2015
北恋
北恋 2020-11-30 10:19

I found this snippet of code in my travels in researching JSON:

var array = typeof objArray != \'object\' ? JSON.parse(objArray) : objArray;
<
相关标签:
4条回答
  • 2020-11-30 10:33

    It's the ternary conditional operator -- basically,

    if (condition) {
       a = 4;
    }
    else {
       a = 5;
    }
    

    becomes

    a = condition ? 4 : 5;
    
    0 讨论(0)
  • 2020-11-30 10:35

    That’s called the conditional operator:

    condition ? expr1 : expr2
    

    If condition is true, the operator returns the value of expr1; otherwise, it returns the value of expr2.

    0 讨论(0)
  • 2020-11-30 10:45

    It's called a Conditional (ternary) Operator. It's essentially a condensed if-else.

    So this:

    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    

    ...is the same as this:

    var array;
    if (typeof objArray != 'object') {
        array = JSON.parse(objArray);
    } else {
        array = objArray;
    }
    
    0 讨论(0)
  • 2020-11-30 10:59

    Just read it like this:

    result = (condition) ? (true value) : (false value);
    

    place what ever you like in the 3 operators.

    As many has compared it to an IF.. THEN structure, so it is.

    0 讨论(0)
提交回复
热议问题