为什么第二个代码片段给出错误,而第一个代码片段对于 JS 运行良好?

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

我正在学习 JavaScript 中的词法环境并遇到此错误。 有错误的代码片段:

let x = 1;

function func() {
  console.log(x); 
  let x = 2;
}

func();

但是这段代码运行正确:

let x = 1;

function func() {
  console.log(x);
}

func(); //logs out 2

我希望第一个代码片段记录值 1,然后给出 x 已被声明的错误,但它却给了我 console.log(x) 部分的参考错误。

javascript scope lexical-scope
1个回答
0
投票

该问题与 JavaScript 中的提升有关。 let 关键字是块作用域的,并且被提升到块的顶部但未初始化。在第一个代码片段中,console.log(x) 在块内声明和初始化变量 x 之前遇到该变量,从而导致引用错误。在第二个代码片段中,变量 x 在 console.log(x) 语句之前声明并初始化,避免了错误。

let x = 1;
function func() {
  let x = 2;
  console.log(x);
}
func();
© www.soinside.com 2019 - 2024. All rights reserved.