gpt4 book ai didi

Javascript let 双重声明

转载 作者:行者123 更新时间:2023-12-05 01:58:44 24 4
gpt4 key购买 nike

我知道 let 在 JS 中不能声明变量两次。但是当我在控制台中尝试以下代码时:

a = 1;
let a = 2;
let a = 3;
.
.
.
let a = 100;

注意:它们是逐行运行的(如下面的屏幕截图所示)。版本为谷歌浏览器91.0.4472.114

enter image description here

它总是有效,没有错误。这真的让我很困惑,为什么它工作正常?我知道控制台中发生的事情并不代表脚本中发生的事情。但我的问题是为什么它存在于控制台中?这有什么原因吗,或者它可能是一个错误?

因为我假设 let 和 const 具有相同的声明行为,如果我使用 const 而不是 let,这是毫无疑问的。

b = 1;
const b = 2;
const b = 3; //Uncaught SyntaxError: Identifier 'b' has already been declared

enter image description here

最佳答案

这是 Chrome 的一项显式功能,仅此而已。它正在为您处理事情,以便您在摆弄测试时不会遇到“x is already defined”的障碍。

It was added in Chrome 80 .

The Console now supports redeclarations of let and class statements. The inability to redeclare was a common annoyance for web developers who use the Console to experiment with new JavaScript code.

编辑:

我刚刚发现 Chrome 92 ,即将推出,也将添加对 const 重新声明的支持!

This allows developers to copy-paste code into the DevTools console to see how it works or experiment, make small changes to the code, and repeat the process without refreshing the page. Previously, DevTools threw a syntax error if the code redeclared a const binding.

关于Javascript let 双重声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68355442/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com