[英]Is it possible to get the two values from conditional(ternary) operator in javascript?
Here I have the following javascript code, with the two values. 在这里,我有以下带有两个值的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));
Here i want to check the three conditions. 在这里,我想检查三个条件。
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.
above code is showing not giving the w and values showing javascript error, how to get those values with the ternary operator, with out using if and else conditions. 上面的代码没有显示w和显示javascript错误的值,如何使用三元运算符获取这些值,而没有使用if和else条件。
Please help me. 请帮我。
Thanks in advance 提前致谢
Yes, you can return an array (alternatively an object) from the conditional operator, and assign values from the array: 是的,您可以从条件运算符返回一个数组(或者一个对象),并从该数组分配值:
var values = w == h ? [350, 350] : w < h ? [300, 350] : [350, 300];
w = values[0];
h = values[1];
Your original code should actually work, it does when I test it. 您的原始代码应该可以正常工作,在我测试时可以。 However, you are misusing the conditional operator. 但是,您滥用了条件运算符。 If you want to do the assignment directly and not return a value, you should not use the conditional operator, but just an if
statement: 如果要直接进行赋值而不返回值,则不应使用条件运算符,而应使用if
语句:
if (w == h) {
w = 350; h = 350;
} else if (w < h) {
w = 300; h = 350;
} else {
w = 350; h = 300;
}
Another solution (which is longer) is by using closure and immediately executed function: 另一个解决方案(更长)是使用闭包并立即执行函数:
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.