为什么只有在代码编辑器中重新分配 const 才会在控制台中产生错误?
Why reassigning const producing error in console only if we do that in code editor?
我在代码编辑器中编写了以下代码产生了错误:
const a = 1;
console.log(a);
const a = 1; // Uncaught SyntaxError: Identifier 'a' has already been declared
我直接在控制台中做了同样的事情 --
const a = 1; //undefined
const a = 1; //undefined
const a = 2; // undefined
a // 2
为什么这里的错误没有被捕获?
假设您使用的是 Chrome,这是设计使然。 const
重新声明是在 Chrome Devtools 92 中有意实施的,目的是让开发人员更容易在 Chrome 控制台中测试代码:
The Console now supports redeclaration of const statement, in addition
to the existing let and class redeclarations. The inability to
redeclare was a common annoyance for web developers who use the
Console to experiment with new JavaScript code.
正如博客 post 指出的那样,它使您能够重新声明 const
和您通常无法重新声明的其他绑定。这意味着:
> const a = 1;
> const a = 2;
是允许的,因为两行代码在单独的 REPL 脚本中执行(由 >
表示),同时执行:
> const a = 1;
const a = 2;
x Uncaught SyntaxError: Identifier 'a' has already been declared
是不允许的,因为这是在一个 REPL 脚本中重新声明 const
(多行代码可以使用 SHIFT + 输入)。
此更改仅适用于 Chrome devtools 控制台,而不适用于常规页面脚本,如果您尝试重新声明 const
.
,它将按预期抛出 SyntaxError
我在代码编辑器中编写了以下代码产生了错误:
const a = 1;
console.log(a);
const a = 1; // Uncaught SyntaxError: Identifier 'a' has already been declared
我直接在控制台中做了同样的事情 --
const a = 1; //undefined
const a = 1; //undefined
const a = 2; // undefined
a // 2
为什么这里的错误没有被捕获?
假设您使用的是 Chrome,这是设计使然。 const
重新声明是在 Chrome Devtools 92 中有意实施的,目的是让开发人员更容易在 Chrome 控制台中测试代码:
The Console now supports redeclaration of const statement, in addition to the existing let and class redeclarations. The inability to redeclare was a common annoyance for web developers who use the Console to experiment with new JavaScript code.
正如博客 post 指出的那样,它使您能够重新声明 const
和您通常无法重新声明的其他绑定。这意味着:
> const a = 1;
> const a = 2;
是允许的,因为两行代码在单独的 REPL 脚本中执行(由 >
表示),同时执行:
> const a = 1;
const a = 2;
x Uncaught SyntaxError: Identifier 'a' has already been declared
是不允许的,因为这是在一个 REPL 脚本中重新声明 const
(多行代码可以使用 SHIFT + 输入)。
此更改仅适用于 Chrome devtools 控制台,而不适用于常规页面脚本,如果您尝试重新声明 const
.