javascript - 试图了解全局 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。
先感谢您。
解决方案
啊,我意识到我没有在 for 循环中更新 tempcount,而是应该写成:
for(tempcount ; myQuestions.length-1;tempcount++){
之前,它不更新 tempcount,而后者又不更新 currentcount。
感谢其他所有回答的人,这也很有帮助!
推荐阅读
- javascript - 在 PHP 中更新现有表的数据
- mysql - TypeORM - 按匹配的 OR 数量排序
- azure - 计划-Azure Resource-Group 成本分析月度出口计费发票
- django - 如何更新实时 django 网站上的包/依赖项?
- sql - 将 MongoDB NoSQL 复制到 SQL 表中的最佳方法
- google-api - 通过 Adsense API 获取银行账户信息
- php - 如何在 Laravel 中使用资源编写验证规则?
- javascript - 猫鼬模式字段内的对象
- vba - 有什么办法可以防止某些动作记录在宏中?
- java - 图像文件以实际大小的两倍写入