首页 > 解决方案 > 如何让 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;
}

标签: javascriptfunctionswitch-statement

解决方案


目前,您在每种情况下都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";
}

模板文字


推荐阅读