Javascript - if语句错误

Javascript - if statement error

本文关键字:错误 语句 if Javascript      更新时间:2023-09-26

想知道是否有人可以引导我进入正确的方向,我正试图使用Javascript制作一个小游戏来帮助我学习。从本质上讲,我声明我所有的变量,我想改变我的函数之外,所以他们行动全局,这在代码中工作,但if语句似乎没有证明成功,我似乎不能纠正这一点作为教程指向我的代码是正确的,请参阅下面的代码;

var Refresh;
Refresh = "InActive";
var Counter;
Counter = 0;
var StartTime;

function StartGame() {
    var StartDate;
    StartDate = new Date();
    StartTime = d.getTime();
    Refresh = "Active";
}

function FunctionB1() {
    if (Refresh == "Active"){
        document.getElementById("Bean1").style.display = "None";
        Counter ++;
        document.getElementById("BeanCount").innerHTML = Counter + " Out of 150";
    }
}

需要将d.getTime();改为StartDate.getTime();,以反映变量名的变化

function StartGame() {
StartTime = new Date().getTime();
Refresh = "Active";
}

JSFiddle:解决方案

编辑,包括Xufox的改进

尝试从StartGame()函数返回变量Refresh。它看起来像这样:

function StartGame() {
    var StartDate;
    StartDate = new Date();
    StartTime = d.getTime();
    Refresh = "Active";
    return Refresh;
}
function FunctionB1() {
    var startRefresh = StartGame();
    if (startRefresh == "Active"){
        document.getElementById("Bean1").style.display = "None";
        Counter ++;
        document.getElementById("BeanCount").innerHTML = Counter + " Out of 150";
    }
}
FunctionB1(); // Call the function

刷新变量在调用StartGame()后变得可访问。你不能访问FunctionB1中的Refresh变量,因为它还没有被声明。试试这样

function StartGame() {
    Refresh = "Active";
}
function FunctionB1() {
    if (Refresh == "Active"){
        console.log('done');
    }
}
function Game() {
    StartGame()
    FunctionB1()
    console.log(Refresh) // Active
};