开发者

What does this javascript code do? [duplicate]

开发者 https://www.devze.com 2023-03-23 03:54 出处:网络
This question already has answers here: Question mark and colon in JavaScript (8 answers) Closed 8 years ago.
This question already has answers here: Question mark and colon in JavaScript (8 answers) Closed 8 years ago.
y = x?0:0x80
开发者_如何学C

From googling the colon seems to be a ternary operator.


That's right. (The correct name is the conditional operator. It is a ternary operator, in that it takes three operands, but it's commonly misnamed the ternary operator because it's the only JavaScript operator that does so.)

The code is roughly equivalent to this:

var y;
if (x) {
    y = 0;
}
else {
    y = 0x80;
}


It is a ternary operator. It assigns 0 to y if x is true, otherwise it assigns 0x80.


Yes, it's a ternary operation, assigning y the value of 0 if x is true or 0x80 otherwise.


It translates to:

if(x) then
    y=0
else
    y=0x80

But is much shorter.


Yes to all of the above, but it is also checking for the existence of x. If x doesn't exist or is null, y = 0x80.

0

精彩评论

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