简体   繁体   中英

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. 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. This is the case even if I substract 1 before closing the while loop.

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. So you need to declare another variable inside the while block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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