javascript函数中的重写变量
首先我想说的是,我在javascript中搜索了一些关于作用域变量的信息,例如,我试图理解为什么我的代码会这样,但最后我真的不知道。我不能在函数中的函数中重写var a,我只能使用a=6;没有变量。为什么在if语句之前未定义变量并重写此变量?为什么没有这样的结果: 五, 等于5 等于6 我有类似的东西: 未定义 不等于5 等于6 这是我的密码:javascript函数中的重写变量,javascript,variables,scope,Javascript,Variables,Scope,首先我想说的是,我在javascript中搜索了一些关于作用域变量的信息,例如,我试图理解为什么我的代码会这样,但最后我真的不知道。我不能在函数中的函数中重写var a,我只能使用a=6;没有变量。为什么在if语句之前未定义变量并重写此变量?为什么没有这样的结果: 五, 等于5 等于6 我有类似的东西: 未定义 不等于5 等于6 这是我的密码: var a = 5; function something(){ console.log(a); if(a == 5){
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();
这是因为javascript变量 您的代码等于:
var a = 5;
function something(){
var a; // here
console.log(a); // a is the local variable which is undefined
if(a == 5){
console.log('equal 5')
}
else{
console.log('not equal 5'); // a is undefined so not equal 5
}
a = 6; // a is assigned to 6
function test(){
if(a == 6){
console.log('equal 6'); // a is 6 here
}
else{
console.log('not equal 6')
}
}
test();
}
something();
这是因为javascript变量 您的代码等于:
var a = 5;
function something(){
var a; // here
console.log(a); // a is the local variable which is undefined
if(a == 5){
console.log('equal 5')
}
else{
console.log('not equal 5'); // a is undefined so not equal 5
}
a = 6; // a is assigned to 6
function test(){
if(a == 6){
console.log('equal 6'); // a is 6 here
}
else{
console.log('not equal 6')
}
}
test();
}
something();
因为当您第二次声明var a=6时,您正在重写a的第一次声明,即var a=5。因此,当您定义函数something时,a尚未定义,因此console.loga返回undefined
但是,当您将a的第二个声明替换为a=6时,第一个声明仍然有效,您只需在之后更改a的值,就可以得到预期的结果:
5
equal 5
equal 6
有关更多讨论,请参阅。因为当您第二次声明var a=6时,您将覆盖a的第一次声明,即var a=5。因此,当您定义函数something时,a尚未定义,因此console.loga返回undefined
但是,当您将a的第二个声明替换为a=6时,第一个声明仍然有效,您只需在之后更改a的值,就可以得到预期的结果:
5
equal 5
equal 6
有关更多讨论,请参阅