-1

我是一般的代码新手,我正在学习 javascript,几天前我做了一个“路径检查器”,只是为了看看我能用我目前的知识做什么,现在 1 周后我正在尝试改进它,更少的代码,更多可重用的函数,但我不知道为什么不能正确运行,单独的逻辑很好,但变量不起作用。

这是基本逻辑。

let moto1='';

function checkMoto1() {
    if (myMotosInTheGarage === 0 && moto1 === '') {
        openAlert(displaySorryAlert); //global function that works
    } else if (myMotosInTheGarage === 0 && moto1 === 'out') {
        moto1 = 'return';    //change status
        myMotosInTheGarage++; //sum to a count
        countMotos; //const of write the myMotosInTheGarage in a textContent
        changeBackground(btn1, 'red'//global function that works
    } else if (myMotosInTheGarage >= 0) {
        if (moto1 === '') {
            moto1 = 'out';
            myMotosInTheGarage--;
            countMotos;
            changeBackground(btn1, 'green');
        } else if (moto1 === 'out') {
            moto1 = 'return';
            myMotosInTheGarage++;
            countMotos;
            changeBackground(btn1, 'red');
        }
    }
}

我尝试将其用于全局功能。

let moto1='';

function checkMoto1() {
    checkMotoGarage(moto1, btn1);
};

function checkMotoGarage(motonumber, btnnumber) {
    if (myMotosInTheGarage === 0 && motonumber === '') {
        openAlert(displaySorryAlert);
    } else if (myMotosInTheGarage === 0 && motonumber === 'out') {
        motonumber = 'return';
        myMotosInTheGarage++;
        countMotos;
        changeBackground(btnnumber, 'red');
        console.log(`the ${btnnumber} it's ${motonumber}`);
    } else if (myMotosInTheGarage >= 0) {
        if (motonumber === '') {
            motonumber = 'out';
            myMotosInTheGarage--;
            countMotos;
            changeBackground(btnnumber, 'green');
            console.log(`the ${btnnumber} it's ${motonumber}`);
        } else if (motonumber === 'out') {
            motonumber = 'return';
            myMotosInTheGarage++;
            countMotos;
            changeBackground(btnnumber, 'red');
            console.log(`the ${btnnumber} it's ${motonumber}`);
        }
    }
};

moto 状态在全局函数中没有改变,这是为什么呢?我做错了什么?

4

2 回答 2

0

我明白了,你需要返回一个值,而不是变量,然后在可重用函数之外用新值更改变量。我严重认为你可以以某种方式更改可重用函数内部的值,这是我的问题,因为在这种情况下,你每次只能有这个函数的一个值?,如何改变里面的值?这是可能的?

function checkMoto1() {
    moto1 = ckeckMotoGarage(moto1, btn1);
    console.log(moto1);
}
function ckeckMotoGarage(motoNumber, btnNumber) {
    if (myMotosInTheGarage >= 0 && motoNumber === '') {
        btnNumber.style.background = 'green';
        btn1.style.borderColor = 'green';
        return 'out';
    } else if (myMotosInTheGarage >= 0 && motoNumber === 'out') {
        btnNumber.style.background = 'red';
        btn1.style.borderColor = 'red';
        return 'return';
    }
}
于 2021-08-19T22:44:35.980 回答
0

在代码的更新版本中,此变量从未更改过:

let moto1='';

在原始工作版本中,代码会更新该变量:

moto1 = 'return';

但在新版本中,您只更新该函数中的局部变量,而不是全局变量

motonumber = 'return';

如果你想维护和更新一个全局变量,你需要更新它:

moto1 = 'return';

或者,您可以从函数返回值(只需记住在返回之前做所有其他需要做的事情)并在调用函数的任何位置分配/使用该值。但是该函数已经在修改其他全局变量,因此您最好与您正在使用的模式保持一致。

于 2021-08-19T18:49:59.170 回答