且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JavaScript 中全局和局部变量的奇怪行为

更新时间:2022-03-20 06:17:48

发生这种情况是因为您的第二个 a 变量被提升"到函数的顶部并且它隐藏了第一个 >a.实际发生的事情是这样的:

This is happening because your second a variable is being 'hoisted' to the top of the function and it hides the first a. What is actually happening is this:

var a = 5;

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

x();

这是一篇关于从足够好的提升提升的文章,以进一步阅读该主题.

Here is an article on hoisting from adequately good for further reading on the subject.