简体   繁体   中英

Using multiple conditions in ? : statements in javascript

In need to check three conditions and assign a value to a variable according the condition.

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

Is it possible to do it in JavaScript using ? : statement to make it as a single line code

Yes, you can use convert it to Conditional(ternary) operator .

 var a = "z3"; var b = a == "z1" ? "one" : a == "z2" ? "two" : a == "z3" ? "three" : "" ; console.log(b); 


FYI : For a better readability, I would suggest using if...else statement or use switch statement . Although you need to use parenthesis for nested ternary operator for avoiding problems in case complex operations.

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

Don't forget that it's tough to read to read this quickly. It's quite ok to use for one if else block.

You can do this things:

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

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 ) ) ); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM