开发者

Does the "condition" (? :) operator work in JavaScript as in C?

开发者 https://www.devze.com 2023-01-23 20:53 出处:网络
Example: var x, y, z; //... x > 10开发者_StackOverflow中文版0 ? y = x : z = x ; Yes it does work the same although operator precedence is always tricky so I would recommend parenthesis to avoid co

Example:

var x, y, z;
//...
x > 10开发者_StackOverflow中文版0 ? y = x : z = x ;


Yes it does work the same although operator precedence is always tricky so I would recommend parenthesis to avoid confusion.

tangentially related..
You can also use || in JavaScript similar to the null coalescing operator ?? in C#


I'm not sure if this works:

x > 100 ? y = x : z = x ;

But this works:

y = x > 100 ? foo : bar ;


Yes, ternary operators work the same way in Javascript. Your example is combining a lot of expressions, so precedence might be an issue. You should parenthesize to ensure precedence.


Yes it works the same in that it has the following basic syntax

condition ? true-expression : false-expression

It only evaluates the expression, and hence processes side effects, for the expression dictated by the conditional.

Here's a link to the Mozilla documentation on the ternary operator

  • https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special/Conditional_Operator


Yes, ternary operators work the same way in Javascript as they do in C, C++, C#, Java, Javascript, Perl, and PHP.


Yes, according to the conditional operator Wikipedia article and the ECMA-262 standard (see section 11.12).


This should help you (in the future):

https://developer.mozilla.org/en/JavaScript/Reference/Operators/Operator_Precedence

First of all the > comparison will be evaluated because it has precedence 8. ?: has precedence 15, lower than 16 for =. This means that the ternary operator will be run before any assignments (i.e. the first operand, the condition, will be evaluated and then only a branch will be chosen).

Also a simple test

//x = 50;
x = 200;
x > 100 ? y = x : z = x ;
alert((typeof y)+'|'+(typeof z));

would have answered you question.


Here's a different approach. You can use the ternary to select the variable as a string within square brackets.

This window assumes y and z are global. Otherwise, you would need to give the proper context.

window[x > 100 ? 'y' : 'z'] = x;
0

精彩评论

暂无评论...
验证码 换一张
取 消