为什么输出未定义? [复制]

问题描述 投票:0回答:2

这是我一直在努力回答的一个棘手的面试问题,更不用说清楚解释为什么此代码输出未定义了。

  var x = 21;
    var girl = function() {
      console.log(x);
      var x = 20;
    };
    girl();

因此,x = 20在console.log下面-Javascript提升了该变量,但为什么不将其输出为20?好的,让我们想象一下,它会忽略在console.log下声明的变量-为什么它不在全局范围内显示?谁能为我讲清楚?我会很感激的。

javascript variables scope hoisting
2个回答
1
投票

代码的“内部表示形式”类似于

var x = 21;
var girl = function() {
  var x;  // (equals `var x = undefined`)
  console.log(x);
  x = 20;
};
girl();

可能会清除它。


0
投票

var的基本范围结果应为“未定义”。var x的声明被提升到函数girl()的顶部,但是将数字20分配给x的初始化仅发生在它所写的行上。

所以代码基本上看起来像这样:

var x; // declaration of x in the outer scope.
var girl; // declaration of girl.
x = 21; // initialization x as the number 21.
girl = function() {
  var x; // declaration of x in the inner scope
  console.log( x ); // should log undefined, since x exists, but has no value.
  x = 20; // initialization of x as the number 20
};
girl(); // run the function
© www.soinside.com 2019 - 2024. All rights reserved.