使用全局变量时函数的行为有所不同
let outsideVariable = 5;
function myFunctionTests(){
let checkBox = document.getElementById("checkTests");
let variableName = 10;
if (checkBox.checked == true){
variableName += 1;
outsideVariable += 1;
console.log('variableName is: ',variableName);
console.log('outsideVariable is: ',outsideVariable);
} else {
variableName -= 1;
outsideVariable -= 1;
console.log('variableName is: ',variableName);
console.log('outsideVariable is: ',outsideVariable);
}
}
当我运行此代码并勾选复选框时,两个变量(“variableName”和“outsideVariable”)都会增加 1(输出为 11 和 6)。到目前为止,一切都很好。
现在,当我取消选中该复选框时,“variableName”会下降 1(基于初始值 10,因此按预期变为 9),但“outsideVariable”会返回到 5,而不是 4。
唯一的方法要使“outsideVariable”变为4,只需更改
outsideVariable -= 1;
到
外部变量 -= 2;
发生这种情况有什么特殊原因吗? 我正在学习 JavaScript,所以请考虑到这一点。
let outsideVariable = 5;
function myFunctionTests(){
let checkBox = document.getElementById("checkTests");
let variableName = 10;
if (checkBox.checked == true){
variableName += 1;
outsideVariable += 1;
console.log('variableName is: ',variableName);
console.log('outsideVariable is: ',outsideVariable);
} else {
variableName -= 1;
outsideVariable -= 1;
console.log('variableName is: ',variableName);
console.log('outsideVariable is: ',outsideVariable);
}
}
When I run this code and I tick the checkbox, both variables ("variableName" and "outsideVariable") go up by 1 (output is 11 and 6). So far so good.
Now when I untick the checkbox, "variableName" goes down by 1 (based on the initial value of 10, so it goes to 9 as expected), but "outsideVariable" goes back to 5, instead of going to 4.
The only way to make "outsideVariable" go to 4 is to change
outsideVariable -= 1;
to
outsideVariable -= 2;
Any special reason why this happens?
I'm learning JavaScript, so take that into consideration.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你想要当复选框取消选中时,variableName = 10 和 OutsideVariable = 5,但它们等于 9 和 4,对吧?对于这个问题,你应该在全局范围之外定义变量名!
you want when checkbox uncheck, variableName = 10 and outsideVariable = 5, but they are equals to 9 and 4, right? for that problem you shoud define variableName in out of scope like global scope!.