首页 > 解决方案 > 如何将条件决定的结果分配给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 的各个方面。

标签: 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'
    }
}

推荐阅读