使用全局变量时函数的行为有所不同

发布于 2025-01-10 09:04:07 字数 902 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萌无敌 2025-01-17 09:04:07

你想要当复选框取消选中时,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!.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文