首页 > 解决方案 > 试图了解全局 javascript 变量的范围

问题描述

我的javascript代码中有这个全局变量:

var currentcount=0;

稍后我尝试更新 currentcount,并以以下方式包含它:

 function next(){
   ...
    if(userAnswer === myQuestions[overallcount].correctAnswer){
      ...
       var tempcount = currentcount;
        for(tempcount in myQuestions.length-1){
          if(currentdiff<myQuestions[tempcount].difficulty)
            currentcount=tempcount;
        }
      ...
  }

当我输出 currentcount 时,它仍然是 0。

我只是无法理解 currentcount 的范围是什么,以及为什么它没有按照我想要的方式更新。tempcount 确实会更新为 currentcount,但 currentcount 永远不会更新。

如果我这样做:

 function next(){
   ...
    if(userAnswer === myQuestions[overallcount].correctAnswer){
      ...
       var tempcount = currentcount;
       currentcount++;
      ...
    }
  }

currentcount 确实更新了,但同样,这不是我想要的方式。

请解释为什么会这样,以及是否有解决方案以我想要的方式更新 currentcount。

先感谢您。

标签: javascriptscope

解决方案


啊,我意识到我没有在 for 循环中更新 tempcount,而是应该写成:

 for(tempcount ; myQuestions.length-1;tempcount++){

之前,它不更新 tempcount,而后者又不更新 currentcount。

感谢其他所有回答的人,这也很有帮助!


推荐阅读