尽管有 if 语句,代码在所有循环中都是 运行
The code is running through all loops despite if statements
我正在使用 ejs。无论我的语句 returns 是什么(无论 currentGame
是什么),我的输出始终是 12。我尝试实现 break;
或 return;
并尝试使用其他循环,例如switch case
或 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")
问题是您的代码正在无条件分配给您的服务器端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。
不过,从您发布的具体代码回过头来看:使用服务器端代码生成客户端代码几乎从来都不是一个好主意。相反,请分别编写您的客户端代码和服务器代码,这样就不会出现这种混淆。
我正在使用 ejs。无论我的语句 returns 是什么(无论 currentGame
是什么),我的输出始终是 12。我尝试实现 break;
或 return;
并尝试使用其他循环,例如switch case
或 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")
问题是您的代码正在无条件分配给您的服务器端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。
不过,从您发布的具体代码回过头来看:使用服务器端代码生成客户端代码几乎从来都不是一个好主意。相反,请分别编写您的客户端代码和服务器代码,这样就不会出现这种混淆。