javascript - 如何让 switch 语句一遍又一遍地运行而不会卡在负载上?
问题描述
switch 语句在 floor() 函数中时工作正常,但是每当变量在函数外更改时它就不会运行,所以我希望 switch 语句一直运行。尝试使用 while 循环,但页面在加载时卡住了。试图将switch语句放在函数之外,但是switch语句没有被触发?至少我是这么认为的,因为什么也没发生。
var level = 0;
function floor() {
level += 1;
switch (level) {
case 1:
if (level = 1) {
document.getElementById("floor1").style.backgroundColor = "black";
}
break;
case 2:
if (level = 2) {
document.getElementById("floor2").style.backgroundColor = "black";
}
break;
case 3:
if (level = 3) {
document.getElementById("floor3").style.backgroundColor = "black";
}
break;
case 4:
if (level = 4) {
document.getElementById("floor4").style.backgroundColor = "black";
}
break;
case 5:
if (level = 5) {
document.getElementById("floor5").style.backgroundColor = "black";
}
case 6:
if (level = 6) {
document.getElementById("floor6").style.backgroundColor = "black";
}
break;
case 7:
if (level = 7) {
document.getElementById("floor7").style.backgroundColor = "black";
}
break;
case 8:
if (level = 8) {
document.getElementById("floor8").style.backgroundColor = "black";
}
break;
case 9:
if (level = 9) {
document.getElementById("floor9").style.backgroundColor = "black";
}
break;
case 10:
if (level = 10) {
document.getElementById("floor10").style.backgroundColor = "black"
}
default:
}
}
function game1true() {
level += 1;
}
function game1false() {
life -= 1;
}
解决方案
目前,您在每种情况下都level
使用单个等号分配值。比较使用==
and===
运算符。例如:
case 1:
if (level === 1) {
document.getElementById("floor1").style.backgroundColor = "black";
}
但是,这里不需要 switch 语句,因为您在所有情况下都分配了黑色。只需level
在选择器中使用。
function floor() {
level += 1;
document.getElementById(`floor${level}`).style.backgroundColor = "black";
}
•模板文字
推荐阅读
- android - 无法解析方法“getMap()”
- javascript - “component1.toLowerCase 不是函数”+ 难以理解高阶函数:/
- c# - 将类型作为多个离散单例实例注入的模式
- postgresql - 摩卡测试无法连接到 postgres 数据库,使用 knex
- asp.net-core-mvc - 在自定义模型绑定器中递归验证复杂模型
- python - 安装和导入修改包
- macos - 如何确定哪个应用程序窗口位于顶部?
- c# - WorkerService 模板是否适合在 DDD 解决方案中创建应用程序核心?
- javascript - 存储 access_token - javascript
- java - 如何在 Fragment 中授予相机权限