为什么不将未定义的var添加到窗口对象JavaScript中?
据我所知,以下声明不会向变量为什么不将未定义的var添加到窗口对象JavaScript中?,javascript,scope,global-variables,undefined,window-object,Javascript,Scope,Global Variables,Undefined,Window Object,据我所知,以下声明不会向变量aa添加任何值: var aa = undefined; function a () { var aa; console.log(aa); // here aa is still undefined if(!aa) { aa = 11; // should add to the globle scope (window Object) bb = 12; // should add to the globl
aa
添加任何值:
var aa = undefined;
function a () {
var aa;
console.log(aa); // here aa is still undefined
if(!aa) {
aa = 11; // should add to the globle scope (window Object)
bb = 12; // should add to the globle scope (window Object)
}
console.log(aa);
console.log(aa); // should be 11
console.log(bb); // should be 12
}
现在,如果我想使用访问变量aa
和bb
,我只能访问bb
而不能访问aa
。
我的问题是为什么不能从外部访问aa
,因为在声明中我没有给它赋值,而且它仍然没有定义
谢谢。尝试删除
var aa代码>从您的函数中
这里发生的事情是。您已将aa
声明为函数a
中的局部变量。局部变量设置为11。尝试删除var aa代码>从您的函数中
这里发生的事情是。您已将aa
声明为函数a
中的局部变量。局部变量设置为11。请看我的评论
var aa = undefined; // global scope
function a () {
if(true) { // useless
var aa; // declare aa in the function scope and assign undefined
// to work on the global aa you would remove the above line
console.log(aa); // here aa is still undefined
if(!aa) {
aa = 11; // reassign the local aa to 11
bb = 12; // assign 12 to the global var bb
}
console.log(aa); // aa is 11
}
console.log(aa); // still in the function scope so it output 11
console.log(bb); // should be 12
}
console.log(aa) // undefined nothing has change for the global aa
要了解更多信息,请阅读我的评论
var aa = undefined; // global scope
function a () {
if(true) { // useless
var aa; // declare aa in the function scope and assign undefined
// to work on the global aa you would remove the above line
console.log(aa); // here aa is still undefined
if(!aa) {
aa = 11; // reassign the local aa to 11
bb = 12; // assign 12 to the global var bb
}
console.log(aa); // aa is 11
}
console.log(aa); // still in the function scope so it output 11
console.log(bb); // should be 12
}
console.log(aa) // undefined nothing has change for the global aa
要了解更多信息,请阅读此您已将aa重新定义为在函数范围内,并且由于您未指定值,它已指定未定义。您正在重新定义函数范围内的变量aafunction@JonathandeM.:那么您的意思是未定义的是分配给变量的值吗?您已将aa重新定义为在函数范围内,既然你没有赋值,它已指定undefinedYou正在重新定义function@JonathandeM.:那么您的意思是undefined
是分配给变量的值吗?那么您的意思是undefined
是分配给变量的值吗?是的,默认值是undefined
,除非您手动分配一个值,var a=undefined
等于var b代码>a===b
谢谢你澄清我的误解。我一直认为var a
是什么都没有
。但是现在我能理解的是,可能会出现一个变量'a',它在这个范围内,但是没有给它赋值。如果我错了,请更正。未定义
是一个特殊值,表示未定义任何内容。所以不定义和不定义是一样的。关于这里的范围,你是说undefined
是在我的例子中分配给变量的值吗?是的,默认值是undefined
,除非手动分配值,var a=undefined
等于var b代码>a===b
谢谢你澄清我的误解。我一直认为var a
是什么都没有
。但是现在我能理解的是,可能会出现一个变量'a',它在这个范围内,但是没有给它赋值。如果我错了,请更正。未定义
是一个特殊值,表示未定义任何内容。所以不定义和不定义是一样的。关于这里的范围