简体   繁体   English

是否可以从javascript中的conditional(ternary)运算符获取两个值?

[英]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.

相关问题 带有两个真 (?) 条件运算符的 Javascript 三元运算符 - Javascript ternary operator with two true (?) conditional operators 在 Javascript 中将两个值与三元运算符组合 - Combine two values with ternary operator in Javascript 如果不满足三元运算符中的条件,是否可以写入两个值 - Is it possible to write two values ​if the condition in the ternary operator is not satisfied JavaScript中具有三元条件和逻辑的运算符优先级和运算符 - Operator Precedence with Ternary Conditional and Logical And operators in JavaScript Javascript 仅用于假表达式的三元条件运算符 - Javascript ternary conditional operator for only false expression 条件(三元)运算符未按预期运行(Javascript) - The Conditional (Ternary) Operator is not working as expected(Javascript) 更简洁的 JavaScript 条件三元运算符替代品? - More concise alternative to JavaScript conditional ternary operator? 如何在JavaScript中使用条件(三元)运算符 - How to use conditional(ternary) operator in javascript JavaScript返回和带有var的三元运算符,可能吗? - Javascript return and ternary operator with var, possible? 是否可以将三元运算符放入开关中? Javascript - is it possible to put a ternary operator inside a switch? Javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM