javascript - 如果语句不起作用,可能是一些基本问题

标签 javascript if-statement syntax

我正在测试一个脚本,并且在特定部分遇到问题。我隔离了给我带来问题的部分。

var target_army = "0";

function test(){
    if (target_army == "0") {
        var target_army = "1";
        alert (target_army);
    } else {
        alert ("nope");
    }
}

该函数运行警报“nope nope”,而 target_army 应为 0。该部分

var target_army = "1";
alert (target_army);

运行正常,但添加 if 语句后就会出错。 有谁知道我在哪里犯了错误?

最佳答案

你的函数test实际上是这样解释的:

function test(){
    var target_army;  // local variable declaration - hoisting! [1]
    if (target_army == "0") {  // the local variable target_army doesn't equal 0
        target_army = "1";
        alert (target_army);
    } else { // so it's a nope
        alert ("nope");
    }
}

[1] https://developer.mozilla.org/en-US/docs/Glossary/Hoisting

你的错误是在函数内部使用var而不是像这样修改全局变量:

var target_army = "0";

function test(){
    if (target_army == "0") { // now the global target_army is copared
        target_army = "1";  // and modified
        alert (target_army);
    } else {
        alert ("nope");
    }
}

关于javascript - 如果语句不起作用,可能是一些基本问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35466582/

相关文章:

javascript - jQuery-steps:禁用点击提交

javascript - 将枚举传递给函数不起作用

javascript - 如何禁用客户端点击链接按钮或图像按钮

php - PHP IF 中的比较顺序

Python:一次尝试多次,除了

python - `If` 行的语法错误

javascript - Netbeans 中用于 Javascript 的 SOUT 快捷方式

if-statement - Lua是否具有OR比较?

vba - 多行 If 语句

c# - 函数名前的波浪号在 C# 中是什么意思?