2016-11-17 44 views
2

需要檢查三個條件並根據條件爲變量賦值。在多個條件中使用? :javascript中的語句

if(a =="z1"){ 
    b = "one"; 
} else if(a =="z2"){ 
    b = "two"; 
} else if(a =="z3"){ 
    b = "three"; 
} 

是否可以在JavaScript中使用? :聲明使其成爲單行代碼

+1

___Java == JavaScript___ – Rayon

+0

'b = [ '一個', '2', '3'] [A [1] -1 ]' –

回答

4

是的,您可以使用將其轉換爲Conditional(ternary) operator

var a = "z3"; 
 
var b = a == "z1" ? "one" : a == "z2" ? "two" : a == "z3" ? "three" : "" ; 
 

 
console.log(b);


FYI:爲了更好的可讀性,我會建議使用 if...else語句或使用 switch聲明。儘管在複雜操作的情況下需要使用括號來嵌套三元運算符,以避免出現問題。

+1

但你不應該! – Rayon

+0

@Rayon:爲什麼不呢? –

+0

1)不必要2)不可讀3)與傳統的'if-else'條件相比沒有優勢... – Rayon

1
var b = (a =="z1") ? "one" : ((a =="z2") ?"two":(a =="z3")?"three":null); 

不要忘了,閱讀這篇文章很難。 如果使用一個if else塊,則可以使用。

1

你可以做這樣的事情:???

B =(A == 「Z1」, 「一個」 :(一== 「Z2」, 「二」 :(一== 「Z3」「三「:!未定義)))

1
var b = a == "z1" ? "one" : (a == "z2" ? "two" : (a == "z3" ? "three" : undefined)) ; 

a = "z1" 
 

 
alert(a == "z1" ? "one" : (a == "z2" ? "two" : (a == "z3" ? "three" : undefined))); 
 

 
a = "z2" 
 

 
alert(a == "z1" ? "one" : (a == "z2" ? "two" : (a == "z3" ? "three" : undefined))); 
 

 
a = "z3" 
 

 
alert(a == "z1" ? "one" : (a == "z2" ? "two" : (a == "z3" ? "three" : undefined))); 
 

 
a = "z4" 
 

 
alert(a == "z1" ? "one" : (a == "z2" ? "two" : (a == "z3" ? "three" : undefined)));