具有多个条件的JS三元函数?

我一直在 JavaScript 中使用三元运算符来根据用户输入修改对象的值.我有以下代码,它应该运行:

I have been using a ternary operator in JavaScript to modify the value of an object based on user input. I have the following code, which runs as it should:

var inputOneAns = inputOne == "Yes" ? "517" : "518";

如您所见,我将一个数字字符串值分配给 inputOneAns,无论用户输入的是是"还是否".但是,可能存在用户没有选择值的情况(因为它不是必需的).如果此输入留空,我想将一个空字符串"分配给 inputOneAns.有没有办法或我将一个三元运算符嵌入另一个三元运算符中?为了帮助澄清,这是我想用我的三元函数但使用 if else 语句来完成的相同函数?

As you can see, I am assigning a numeric string value to inputOneAnswhether a user has inputed "Yes" or "No". However, there may be a case that a user has not selected a value (as it is not required). If this input was left blank, I would like to assign an empty string "" to inputOneAns. Is there a wayf or me to embed an ternary operator inside of another ternary operator? To help clarify, here is the same function that I want to accompolish with my ternary function but with if else statements?

if (inputOne == "Yes"){
    var inputOneAns = "517"
}else if (inputOne == "No"{
    var inputOneAns = "518"
}else{
    var inputOneAns = ""
}

是否可以在一个三元函数中包含多个表达式?有没有更好的方法来完成我正在寻找的东西?提前感谢您的提示.

Is it possible to include multiple expressions into a ternary function? Is there a better way to accomplish what I am looking for? Thanks for the tips in advance.

推荐答案

是的,你可以疯狂地嵌套三元组.我觉得这个版本相当易读:

Yes you can go wild nesting ternaries. I find this version to be fairly readable:

var foo = (
  bar === 'a' ? 1 : // if 
  bar === 'b' ? 2 : // else if 
  bar === 'c' ? 3 : // else if
  null // else 
);

但这并不是一个广泛认同的观点,在团队中工作时您可能应该坚持使用 if/elseswitch.

but that's not a widely shared opinion, and you should probably stick to if/else or switch when working on a team.

相关文章