JavaScript 三元 if 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6017132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript ternary if statement
提问by KoolKabin
I would like to know what's the shortcode of if in javascript?
我想知道 javascript 中 if 的简码是什么?
Like in php:
就像在 php 中一样:
$res = ($x > $y)? $x: $y;
What's its conversion in javascript?
它在 javascript 中的转换是什么?
回答by Darkzaelus
It's the same in javascript :)
它在 javascript 中是一样的 :)
var res = (x > y) ? x : y;
回答by CL22
var x = 2;
var y = 3;
var res = (x > y)? x: y;
Although perhaps the following would be better:
虽然也许以下会更好:
var res = Math.max(x, y);
回答by cbz
It is the same in javascript:
在 javascript 中也是一样的:
res = (y < x) ? x : y;
or res = (x > y) ? x : y;
res = (y < x) ? x : y;
或者 res = (x > y) ? x : y;
回答by Majid Fouladpour
The same. It is called ternary:
相同。它被称为三元:
var x = 10, y = 50, res = 0;
res = (x > y) ? x : y;
alert(res);
回答by helle
Here you are: var res = x>y?x:y;
这个给你: var res = x>y?x:y;