首页 > 解决方案 > 尽管有 if 语句,但代码仍在运行所有循环

问题描述

我正在使用ejs。无论我的语句返回什么(无论是什么currentGame),我的输出总是 12。我尝试过实现break;orreturn;并尝试使用其他循环,例如switch caseor while,但它没有帮助。
如果我console.log在每个循环中进行,我会得到 {1, 2, 3...12} 作为输出。

"<%var x%>"

  "<%for(var i=1; i<=12; i++){%>"
  if(currentGame === "<%=i%>"){
      "<%x=i;%>"
  }

"<%}%>"
console.log("<%=x%>")

我在浏览器中得到的结果代码是:

        ""

  ""
  if(currentGame === "1"){
      ""
  }

""
  if(currentGame === "2"){
      ""
  }

""
  if(currentGame === "3"){
      ""
  }

""
  if(currentGame === "4"){
      ""
  }

""
  if(currentGame === "5"){
      ""
  }

""
  if(currentGame === "6"){
      ""
  }

""
  if(currentGame === "7"){
      ""
  }

""
  if(currentGame === "8"){
      ""
  }

""
  if(currentGame === "9"){
      ""
  }

""
  if(currentGame === "10"){
      ""
  }

""
  if(currentGame === "11"){
      ""
  }

""
  if(currentGame === "12"){
      ""
  }

""
console.log("12")

标签: javascriptejs

解决方案


问题是您的代码无条件地x分配给您的服务器端变量,这里:

"<%var x%>"

"<%for(var i=1; i<=12; i++){%>"
if(currentGame === "<%=i%>"){
    "<%x=i;%>" // <===================================
}

"<%}%>"
console.log("<%=x%>")

if客户端代码,它对服务器端逻辑没有任何影响。该代码中的服务器端逻辑如下所示:

var x

for(var i=1; i<=12; i++){
    x=i;
}

这是问题所在。x永远是 12。


但是,从您发布的特定代码退一步:使用服务器端代码生成客户端代码几乎从来都不是一个好主意。相反,分别编写您的客户端代码和您的服务器代码,这样就不会出现这种混乱。


推荐阅读