簡體   English   中英

是否可以從javascript中的conditional(ternary)運算符獲取兩個值?

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM