我正在测试一个脚本,并且在特定部分遇到问题。我隔离了给我带来问题的部分。
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/