What is “?:” notation in JavaScript?

杀马特。学长 韩版系。学妹 提交于 2019-11-27 04:50:42
Matt Huggins

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

It's the ternary conditional operator -- basically,

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

becomes

a = condition ? 4 : 5;

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!