我有2个布尔值boolA和boolB。
我想要一个单独的switch-case语句,它接受四种可能的组合中的每一种,
即像

switch(boolA boolB){
  case 0 0:
    [do something];
  case 0 1:
    [do something else];
  case 1 0:
    [do another thing];
  case 1 1:
    [do the other thing];


基本上,我希望转换案例将两个布尔值解释为单个2位数字。

更新:我决定只使用普通的if-else东西。

最佳答案

我认为我不会那样做。

但是,如果您确实愿意,可以使用boolA + " " + boolB

switch(boolA + " " + boolB){
  case "false false":
    [do something];
    break;
  case "false true":
    [do something else];
    break;
  case "true false":
    [do another thing];
    break;
  default: // "true true"
    [do the other thing];
    break;
}


或者,如果您喜欢数字,请输入(10 * boolA) + boolB

switch((10 * boolA) + boolB){
  case 0:
    [do something];
    break;
  case 1:
    [do something else];
    break;
  case 10:
    [do another thing];
    break;
  default: // 11
    [do the other thing];
    break;
}


规范中保证了所有这些隐式转换。

10-06 07:56
查看更多