首先,我想说我正在搜索有关javascript范围变量的一些信息(例如What is the scope of variables in JavaScript?),我试图理解为什么我的代码的行为如此,但最后我真的不知道。我不能在函数中重写var a,我只能使用a = 6;
而不使用var。为什么a在if语句之前未定义并覆盖此变量?为什么会出现这样的没有结果:覆盖javascript函数中的变量
等于5
等于6
我有这样的事情,而不是:
不确定
不等于5
等于6
这里是我的代码:
var a = 5;
function something(){
console.log(a);
if(a == 5){
console.log('equal 5')
}
else{
console.log('not equal 5');
}
var a = 6;
function test(){
if(a == 6){
console.log('equal 6');
}
else{
console.log('not equal 6')
}
}
test();
}
something();