JS三元函数具有多个条件? [英] JS Ternary functions with multiple conditions?

查看:216
本文介绍了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 / else switch

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

这篇关于JS三元函数具有多个条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆