JS Ternary functions with multiple conditions?(具有多个条件的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三元函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:具有多个条件的JS三元函数?
基础教程推荐
- Bokeh Div文本对齐 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
