![](/img/trans.png)
[英]Javascript ternary operator with two true (?) conditional operators
[英]Is it possible to get the two values from conditional(ternary) operator in javascript?
在这里,我有以下带有两个值的javascript代码。
var w = $("#id1").val();
var h = $("#id2").val();
(w == h) ? (w=350 , h=350):((w<h)?(w=300 , h=350):(w=350 , h=300));
在这里,我想检查三个条件。
1) If w == h then we need to assign some values.
2)else if w < h then we need to assign some other values.
3)else if w > h then we need to assign some other values.
上面的代码没有显示w和显示javascript错误的值,如何使用三元运算符获取这些值,而没有使用if和else条件。
请帮我。
提前致谢
是的,您可以从条件运算符返回一个数组(或者一个对象),并从该数组分配值:
var values = w == h ? [350, 350] : w < h ? [300, 350] : [350, 300];
w = values[0];
h = values[1];
您的原始代码应该可以正常工作,在我测试时可以。 但是,您滥用了条件运算符。 如果要直接进行赋值而不返回值,则不应使用条件运算符,而应使用if
语句:
if (w == h) {
w = 350; h = 350;
} else if (w < h) {
w = 300; h = 350;
} else {
w = 350; h = 300;
}
另一个解决方案(更长)是使用闭包并立即执行函数:
w == h ? function(){w = 350; h = 350}() :
w < h ? function(){w = 300; h = 350}() :
function(){w = 350; h = 300}();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.