我正在测试一个脚本并且遇到了特定部分的问题。我隔离了那些给我带来问题的部分。
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语句就出错了。 有没有人知道我在哪里傻逼?
答案 0 :(得分:1)
您的函数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");
}
}