简体   繁体   中英

Nest function update global variable Javascript

I am wondering why the global variables x and y are not updating from the function 'move' in the while loop. Can anyone please explain why this is not working and how I should fix it?

var x = 10;
var y = 7;
var destX = 5;
var destY = 5;

function simulate(x, y) {
    while (x !== destX && y !== destY) {
        move(x, y);
    }
    console.log("arrived")
}

function move(x, y) {
        if (y !== destY) {
            if (destY > y) {
                y = y + 1;
            } else {
                y = y - 1;
            }
        } else {
            if (destX > x) {
                x = x + 1;
            } else {
                x = x - 1;
            }
        }
}

simulate(x, y);

The parameters to the function are also named x and y , so they are shadowing the global variables. In this particular case, it seems that you only want to use the global variables, so you can simply remove the parameters from both functions.

var x = 10;
var y = 7;
var destX = 5;
var destY = 5;
function simulate() {
    while (x !== destX && y !== destY) {
        move();
    }
    console.log("arrived")
}
function move() {
        if (x !== destX) {
            if (destY > y) {
                y = y + 1;
            } else {
                y = y - 1;
            }
        } else {
            if (destX > x) {
                x = x + 1;
            } else {
                x = x - 1;
            }
        }
}
simulate();

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