需要检查三个条件并根据条件为变量赋值。
if(a =="z1"){
b = "one";
} else if(a =="z2"){
b = "two";
} else if(a =="z3"){
b = "three";
}
是否可以在JavaScript中使用? :声明将其作为单行代码
答案 0 :(得分:4)
是的,您可以将其转换为Conditional(ternary) operator。
var a = "z3";
var b = a == "z1" ? "one" : a == "z2" ? "two" : a == "z3" ? "three" : "" ;
console.log(b);

<小时/> 仅供参考:为了更好的可读性,我建议使用
if...else
语句或使用switch
语句。虽然您需要对嵌套三元运算符使用括号,以避免在复杂操作的情况下出现问题。
答案 1 :(得分:1)
var b = (a =="z1") ? "one" : ((a =="z2") ?"two":(a =="z3")?"three":null);
不要忘记阅读这篇文章很难阅读。 它可以用于一个if else块。
答案 2 :(得分:1)
你可以这样做:
b =(a ==“z1”?“one”:( a ==“z2”?“two”:( a ==“z3”?“three”:undefined)))
答案 3 :(得分: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 ) ) );
&#13;