变量未更改 Javascript

Variable Not Changing In Javascript

我最近开始使用 ProcessingJS 库在 Javascript 中编码。我完成了可汗学院的 JS 课程。我有一个函数,当 x 和 y 位于选定区域时。它应该停止循环,移动 x 和 y,并将 score1X 和 score1Y 移动到 0,然后开始循环。 score1X 和 score1Y 没有移动。该函数在 draw = function 中调用。非常感谢!

var CreatePoint = function(score1X, score1Y) {
    if (x >= score1X - 10 && x <= score1X + 10 && y >= score1Y - 10 && y <= score1Y + 10){
        noLoop();    
        points ++;
        x -= 10;
        y -= 10;
        score1X = 0;
        score1Y = 0;
        loop();
    }
    else if (points <= 0) {
        ellipse(score1X, score1Y, 20, 20);
    }
};

draw = function() {    
    fill(255, 255, 255);
    text(points + "/5", 20, 20);
    CreatePoint(score1X, score1Y);
    CreatePoint(score2X, score2Y);
    CreatePoint(score3X, score3Y);
    CreatePoint(score4X, score4Y);
    CreatePoint(score5X, score5Y);
};

你不能通过赋值给函数参数变量来影响调用者的变量,因为Javascript参数是通过引用传递的。您需要 return 新值,调用者可以将其分配给变量。

var CreatePoint = function(score1X, score1Y) {
    if (x >= score1X - 10 && x <= score1X + 10 && y >= score1Y - 10 && y <= score1Y + 10){
        noLoop();    
        points ++;
        x -= 10;
        y -= 10;
        score1X = 0;
        score1Y = 0;
        loop();
    }
    else if (points <= 0) {
        ellipse(score1X, score1Y, 20, 20);
    }
    return [score1X, score1Y];
};

draw = function() {    
    fill(255, 255, 255);
    text(points + "/5", 20, 20);
    var res = CreatePoint(score1X, score1Y);
    score1X = res[0];
    score1Y = res[1];
    res = CreatePoint(score2X, score2Y);
    score2X = res[0];
    score2Y = res[1];
    res = CreatePoint(score3X, score3Y);
    score3X = res[0];
    score3Y = res[1];
    res = CreatePoint(score4X, score4Y);
    score4X = res[0];
    score4Y = res[1];
    res = CreatePoint(score5X, score5Y);
    score5X = res[0];
    score5Y = res[1];
};