【问题标题】:I dont undertand why the console is showing me undefined [duplicate]我不明白为什么控制台显示我未定义 [重复]
【发布时间】:2019-12-20 18:22:01
【问题描述】:

我是编码新手,无法弄清楚以下代码。如果有人能帮我一把,我将深深感激!

function a() {
  function b() {
    console.log(x);
  }
  var x = 2;
  b();
}
var x = 1;
a();

当我运行这段代码时,控制台是2 非常有意义。超级棒!

但是当我运行这段代码时:

function a() {
  b();

  function b() {
    console.log(x);
  }
  var x = 2;
}
var x = 1;
a();

当这段代码运行时,我原以为控制台的答案也是2!但我得到undefined 作为答案。至少我会认为1 可能是答案,以防它不是 2,但永远不会:undefined

有人可以帮帮我吗?

非常感谢!

【问题讨论】:

  • 语句按顺序执行。您在初始化变量之前调用了b()
  • 你没有得到1,因为该变量在不同的范围内。
  • 我知道这个问题有重复,只是现在找不到。
  • 变量提升是函数局部变量的原因,即使声明是在调用之后。
  • 代码从上到下运行...当然x 如果在分配任何内容之前对其进行引用,它将是未定义的。

标签: javascript console undefined


【解决方案1】:

var 声明被提升。

这意味着这些声明在编译时(代码运行之前)被移动到当前作用域(函数)的顶部。

吊装确实移动变量声明,但移动变量赋值

因此,这段代码:

doSomething();
var variable = value; //Declaration with assignment

转化为:

var variable; //Declaration
doSomething();
variable = value; //Assignment

因此,您的代码与以下代码相同:

function a() {
  var x; //x is now undefined
  
  //Function declarations are hoisted as well:
  function b() {
    console.log(x);
  }
  
  b(); //x is still undefined now...

  x = 2; //x is now 2, but your console.log has already run.
}
var x = 1; //This line doesn't affect your code, as the x you log is in different scope, and the internal x shadows this one.
a();

【讨论】:

    【解决方案2】:

    所以 x 在您的第二个示例中未定义,因为您在调用函数 b(即 b())之后初始化了 x(即 var x = 2)。这意味着当你调用函数 b 时程序还不知道 x 是什么,所以当你调用 b() 时,你试图打印一些你还没有在程序中定义的东西。

    第一个示例有效,因为 x 是在函数调用 b 之前定义的

    【讨论】:

    • 所以下面的代码:
    猜你喜欢
    • 1970-01-01
    • 2014-10-13
    • 1970-01-01
    • 1970-01-01
    • 2014-11-20
    • 1970-01-01
    • 2019-04-15
    • 1970-01-01
    • 2021-11-18
    相关资源
    最近更新 更多