What is “?:” notation in JavaScript?

后端 未结 4 2029
北恋
北恋 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: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;
    }
    

提交回复
热议问题