Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
497 views
in Technique[技术] by (71.8m points)

syntax - What is "?:" notation in JavaScript?

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

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

I'm seeing more and more of the ? and : notation. I don't even know what it is called to look it up! Can anyone point me to a good resource for this? (btw, I know what != means).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...