javascript - 尽管有 if 语句,但代码仍在运行所有循环
问题描述
我正在使用ejs。无论我的语句返回什么(无论是什么currentGame
),我的输出总是 12。我尝试过实现break;
orreturn;
并尝试使用其他循环,例如switch case
or 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。
但是,从您发布的特定代码退一步:使用服务器端代码生成客户端代码几乎从来都不是一个好主意。相反,分别编写您的客户端代码和您的服务器代码,这样就不会出现这种混乱。
推荐阅读
- javascript - 在 Javascript 中以最简单的方式验证字符串中的数字(不要使用正则表达式)
- php - 数据表列超出
- hadoop - 根据客户帐户创建分区
- android - 请帮我解决Android中的空指针异常?
- c - 获取 malloc 宏的不相关值 - M_MMAP_THRESHOLD 和 M_ARENA_MAX
- c# - Microsoft Bot Framework WebChat:禁用 AdaptiveCards 提交上一条消息的按钮
- robotframework - 我们可以将全局变量作为参数传递给 Robot 框架中的变量值吗?
- winapi - GetRegionData() 不适用于堆栈分配的缓冲区
- rest - 优步交付 api 返回 404
- c - 无符号长和 uint32_t?