首页 > 解决方案 > 具有多个值的 switch 语句

问题描述

我想知道是否有一种方法可以评估 switch 表达式中的多个值。例如,我只想在 X 和 Y 匹配时应用一个案例。这是我的代码:

switch (x,y) {
  case x >= 0 && x < 150 && y == 150:
    topLeftRight();
  break;
  case x == 150 && y <= 150 && y > 0:
    topRightDown();
  break;
  case y === 0 && x > 0 && x <= 150:
    bottomRightLeft();
  break;
  case x === 0 && y <= 150 && y >= 0:
    bottomLeftUp();
  break;
}

你知道这是否可以通过开关实现?提前致谢 :)

标签: javascriptswitch-statement

解决方案


你需要一个 if 语句

if(x >= 0 && x < 150 && y == 150)
  topLeftRight();
else if(x == 150 && y <= 150 && y > 0)
  topRightDown();
else if(y === 0 && x > 0 && x <= 150)
  bottomRightLeft();
else if(x === 0 && y <= 150 && y >= 0)
  bottomLeftUp();

案例语句适用于检查单个变量是否等于多个事物的列表。例如:

switch(vehicle.type){
  case Boat:
    print("This is a boat")
    break;
  case Car:
    print("This is a car")
    break;
  case default:
    print("This is not a boat or a car")
    break;
}

评估条件时,最好使用if/else if/else语句


推荐阅读