【问题标题】:why is global variable not accessible even if local variable is defined later in code [duplicate]为什么即使稍后在代码中定义了局部变量也无法访问全局变量[重复]
【发布时间】:2014-11-29 05:58:08
【问题描述】:

为什么下面的代码段会产生下面的输出?

代码段:

var a = 10;
function(){
    console.log(a);
    var a = 5;
}

输出:

undefined

【问题讨论】:

标签: javascript scope global-variables local-variables


【解决方案1】:

因为变量被提升在顶部并且在你的函数中你已经声明了变量 var a = 5 ,它与以下相同:

var a = 10;
function(){
    var a; // a = undefined
    console.log(a);//a is not defined so outputs undefined
    a = 5;
    console.log(a);//a is now 5 so outputs 5
}

并且在您的函数范围内声明了 var,它看不到全局变量,而是看到局部变量,即 var a 并且未定义。

【讨论】:

    猜你喜欢
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多