javascript - 如何将条件决定的结果分配给javascript中的变量
问题描述
以下代码工作正常:
var styles = []
if (state == 's1') {
styles = ['inline-block', 'none', 'none']
} else if (state == 's2') {
styles = ['none', 'inline-block', 'none']
} else if (state == 's3') {
styles = ['none', 'none', 'inline-block']
}
然而,在某些语言中,我们可以使它更简洁。我想按照以下方式做一些事情:
var styles =
if (state == 's1') {
['inline-block', 'none', 'none']
} else if (state == 's2') {
['none', 'inline-block', 'none']
} else if (state == 's3') {
['none', 'none', 'inline-block']
}
在javascript中是否有这样的条件赋值 - 或者甚至更好的某种形式match/case
?
更新很多好的答案 - 谢谢!选择一个似乎最接近我的初衷。但是在其中许多方面学习了 javascript 的各个方面。
解决方案
您可以将条件定义为函数
chooseStyle = (state) => {
if (state == 's1') {
return ['inline-block', 'none', 'none']
} else if (state == 's2') {
return ['none', 'inline-block', 'none']
} else if (state == 's3') {
return ['none', 'none', 'inline-block']
}
}
var styles = chooseStyle(state)
switch
或者如果你使用 a代替更好:
chooseStyle = (state) => {
switch(state) {
case 's1':
return ['inline-block', 'none', 'none']
case 's2':
return ['none', 'inline-block', 'none']
case 's3':
return ['none', 'none', 'inline-block']
default:
return ['inline-block', 'none', 'none'] // return the default styles you want, here I choose the styles of 's1'
}
}
推荐阅读
- javascript - React-Native 简单存储错误:无法加载 RocksDB、SQLite 或 AsyncLocalStorage
- jwt - 使用 jjwt 进行 JWT 验证
- c++ - 如何从另一个头文件c ++调用函数
- javascript - 通过 Java Script 获取发布到操作页面的值
- javascript - 如何在 Angular (v6) 中动态地向材料表单添加验证?
- firebase - 在后端服务器中使用 Firebase 身份验证时如何避免命中率限制?
- javascript - es2018 中不区分大小写的字符串操作
- swift - 在 AKPlayer 中播放后尝试录制时 AudioKit 崩溃
- python - 提高文件下载速度
- angular - 如何动态显示/隐藏 mat-table 中的某些行?