简体   繁体   English

如何在不更改 javascript 中的全局变量的情况下更改局部变量?

[英]How do I make changes to a local variable without changing the global variable in javascript?

var i = 100;

function gamePlay() {
       
    while(i >= 0) {
        if (i>0) {
            console.log(i);}
        else{console.log(**i+1**);}
        i--;
    }
}
    

When I increse i by 1 (the part of the code that is bold), I'd like to make that change occur locally.当我将 i 增加 1 时(代码中的粗体部分),我想让该更改发生在本地。 The rest of the code should use global i but the problem is that the change applies globally and the rest of the code stops working when I add 1 to i.其余代码应使用全局 i,但问题是更改适用于全局,当我将 1 添加到 i 时,其余代码停止工作。 This is the case even if I substract 1 before closing the while loop.即使我在关闭 while 循环之前减去 1 也是如此。

Try this:尝试这个:

var i = 100;

function gamePlay() {
    let i2 = i; // local variable

    while(i2 >= 0) {
        if (i2 > 0) {
            console.log(i2);
        }
        else {
            console.log(i2+1);
        }

        i2--;
    }
}

When you declare variables in a function, they are local to that specific function.当您在函数中声明变量时,它们是该特定函数的本地变量。 But when you declare them outside of the function, they are global and can be used anywhere.但是当你在函数之外声明它们时,它们是全局的并且可以在任何地方使用。

In your case var i = 100 is global and can be used in any function.在您的情况下, var i = 100是全局的,可以在任何函数中使用。 So you need to declare another variable inside the while block.因此,您需要在while块中声明另一个变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM