首页 > 解决方案 > 在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 仅定义为一秒钟的值。在非常非常短的一段时间后,变量变成了它的原始值,即为空。谁能帮我弄清楚为什么该变量仅被定义为单选按钮的值一秒钟。谢谢!

标签: javascriptvariablesfor-loop

解决方案


您在 for 循环 var waytoauthenticate = whichformofauthentication[i].value 中再次声明变量。尝试删除 var 因为它已经在外面声明了。希望这可以帮助


推荐阅读