【问题标题】:Switch statement to match several casesswitch 语句以匹配几种情况
【发布时间】:2018-09-14 07:54:55
【问题描述】:

我想编写一个 switch 语句,如果它们都为真,它将通过前两种情况。如果不是,只匹配正确的那个。

var vehicle = {main: false, detail: false};

switch(true) {
   case (states.data.currentState.indexOf('main.vehicle') !== -1):
      vehicle.main = true;
      break;
   case (states.data.currentState === 'main.vehicle.detail):
      vehicle.detail = true;
      break;
 }

我的问题是,在第一次 break 之后 switch 语句结束并且不会转到 case 2。但是,如果我从第一个 case 中删除 break,它将跳转到 case 2 并应用 vm.vehicle.detail = true;即使不满足 case 条件。

所以如果我在第一种情况下删除 break,我的对象无论如何都会是这样的

{ main: true, detail: true }

如果我不这样做,它会看起来像这样

{ main: true, detail: false }

如何在单次运行交换机时同时满足这两个条件?

【问题讨论】:

  • 那么不要使用switch,而是使用两个if...!?
  • @deceze 但开关中有更多状态。我只贴了一个例子。在我的情况下,switch 语句读起来真的很清楚,而且有很多 if 是很糟糕的。
  • 我认为switch的原则是只有1个适合的case。如果您需要更多案例,请检查 if 方面。
  • 我知道你们中的很多人都想提供帮助,但你们没有理解我的意思。可能我描述的不是很清楚。我不一定要寻找其他方法来做到这一点。我只想知道是否可以在 switch 中匹配两种情况。
  • 不,不是。 switch 不是这样工作的。

标签: javascript angularjs switch-statement


【解决方案1】:

为什么不把比较作为对象的值?

var vehicle = {
        main: states.data.currentState.indexOf('main.vehicle') !== -1,
        detail: states.data.currentState === main.vehicle.detail
    };

ES6

var vehicle = {
        main: states.data.currentState.includes('main.vehicle'),
        detail: states.data.currentState === main.vehicle.detail
    };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-21
    • 1970-01-01
    相关资源
    最近更新 更多