javascript - 具有多个值的 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;
}
你知道这是否可以通过开关实现?提前致谢 :)
解决方案
你需要一个 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
语句
推荐阅读
- flutter - 我是否总是必须等待“https://google.bintray.com”在停机维护后才能完全运行,然后才能构建我的颤振应用程序?
- node.js - AWS Fargate 服务中的“导致执行用户进程:执行格式错误”
- git - 为本地浅拷贝切换 git 标签/分支
- sapui5 - 如何控制 MasterDetail 应用程序的边距
- django - 无法重定向到最近创建的详细视图
- angular - Angular 沿应用程序保存 http 响应
- system-verilog - 如何从 1 到 52 System Verilog 生成可合成的伪随机发生器
- python - Blender 使用 Python Pillow libraqm 渲染复杂字体
- java - 增强的 For 循环 - Java
- jquery - jquery 从 li 获取 data-id