[英]Trying to understand the scope of global javascript variables
I have this global variable in my javascript code:我的javascript代码中有这个全局变量:
var currentcount=0;
Later on I try to update currentcount, and it is enclosed in the following manner:稍后我尝试更新 currentcount,它以下列方式包含:
function next(){
...
if(userAnswer === myQuestions[overallcount].correctAnswer){
...
var tempcount = currentcount;
for(tempcount in myQuestions.length-1){
if(currentdiff<myQuestions[tempcount].difficulty)
currentcount=tempcount;
}
...
}
When I output currentcount, it is still 0.当我output currentcount时,还是0。
I am simply having trouble understanding what the scope of currentcount is, and why it is not updating in the way I want it to.我只是无法理解 currentcount 的 scope 是什么,以及为什么它没有按照我想要的方式更新。 tempcount does update to whatever currentcount is, but currentcount never updates.
tempcount 确实会更新为任何 currentcount,但 currentcount 永远不会更新。
If I do something like:如果我做类似的事情:
function next(){
...
if(userAnswer === myQuestions[overallcount].correctAnswer){
...
var tempcount = currentcount;
currentcount++;
...
}
}
currentcount does update, but again, it's not the way I want it to. currentcount 确实会更新,但同样,这不是我想要的方式。
Please provide an explanation as to why it is so and if there is a solution to update currentcount in the manner I want it to.请解释为什么会这样,以及是否有解决方案可以按照我想要的方式更新 currentcount。
Thank you in advance.先感谢您。
Ah, I realized that I was not updating tempcount within the for-loop, Instead, it should've been written at as:啊,我意识到我没有在 for 循环中更新 tempcount,相反,它应该写成:
for(tempcount ; myQuestions.length-1;tempcount++){
Before, it was not updating tempcount, which in turn was not updating currentcount.之前,它不更新 tempcount,而 tempcount 又不更新 currentcount。
Thank you to everyone else who answered though, it was helpful too!感谢其他所有回答的人,这也很有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.