javascript - 在Javascript for循环中未存储变量超过一秒钟
问题描述
在开始之前,我知道 StackOverflow 中还有许多其他关于变量未使用 Javascript 语言存储的文章。但是,这些解决方案主要是简单的,例如在循环外声明变量。不幸的是,这在我的情况下不起作用。这是我的代码:
function authenticationselection() {
var whichformofauthentication =
document.getElementsByName("authenticationtypes")
var len = whichformofauthentication.length
for (i = 0; i < len; i++) {
if (whichformofauthentication[i].checked) {
waytoauthenticate = whichformofauthentication[i].value
console.log(waytoauthenticate)
break
} else {
continue
}
}
}
我已经在 foo 循环之外声明了变量 waytoauthenticate,这意味着它是一个全局变量。当我运行这部分程序时,变量 waytoauthenticate 被设置为单选按钮的值 one(这就是这段代码的用途)。但是,变量 waytoauthenticate 仅定义为一秒钟的值。在非常非常短的一段时间后,变量变成了它的原始值,即为空。谁能帮我弄清楚为什么该变量仅被定义为单选按钮的值一秒钟。谢谢!
解决方案
您在 for 循环 var waytoauthenticate = whichformofauthentication[i].value 中再次声明变量。尝试删除 var 因为它已经在外面声明了。希望这可以帮助
推荐阅读
- amazon-web-services - 如何使用 vagrant 创建 ec2 实例?
- eclipse - 如何在 Eclipse 中同步拆分编辑器窗格?
- javascript - 如何根据键而不是值在 MongoDB 集合中删除文档?
- python - 从二进制文件中解析特定字符串
- reactjs - Context.Consumer 与 useContext() 访问 Context.Provider 传递的值
- rest - UE 4 - 如何通过 webapi 与 Steam 集成设置服务器配置文件
- python-2.7 - 为什么返回 None;dec2asc?
- ionic-framework - 使用cordova时,离子应用程序不会在服务器上运行
- python - 如何在开放端口上保护 python 套接字侦听、发送和接收?
- apache-spark - 从 pyspark 中删除 bigquery 表