javascript - 声明变量和定义变量有区别吗

标签 javascript variables

我尝试在控制台中一行一行地编写以下行

let x = y //throws error "Uncaught ReferenceError: y is not defined"
console.log(x) //throws error "ReferenceError: x is not defined"
let x = 3; //gives error "Uncaught SyntaxError: Identifier 'x' has already been declared"
x = 3 //ReferenceError: x is not defined

现在的问题是,一个变量怎么能同时未定义已声明。两者有什么区别吗。

最佳答案

A letconst变量只能声明一次——也就是说,当你有let <variableName>在范围内,您已声明 <variableName>在该范围内,并且不能在该范围内再次声明它。

来自previously linked question :

When there's assignment, the right-hand side is parsed first; if the right-hand side throws an error, it never gets to the left-hand side, and the variable declared with let never gets properly initialized; it'll stay in the demilitarized zone / temporal dead zone forever

您不能重新声明一个已经声明过的变量,即使在初始化期间尝试赋值会引发错误。

But on line 4, x=3 should do a proper assignment and it should remove x from TDZ. But that also fails. I fail to understand that

变量初始化后(例如,let x 运行),可以将其赋值给。但就像你不能在 let 之前分配给变量一样初始化,你也不能稍后分配给一个变量,当它的初始化没有成功完成时:

x = 'foo';
let x = 'bar';

错误:

Uncaught ReferenceError: x is not defined

这与您尝试时在控制台中发生的事情相同:

let x = y
// Uncaught ReferenceError: y is not defined
// x has not been initialized, so the next line throws:
x = 'foo'
// Uncaught ReferenceError: x is not defined

x仍然没有初始化,所以错误是一样的。

不过,遇到这种事情很奇怪 - 您只能在控制台中看到它。在普通脚本中,抛出的错误将阻止进一步执行,并且变量名永远保持未初始化这一事实无需担心。


以上是早期 Chrome 版本中的问题。但是in Chrome 80+ , 重新声明 let现在允许,所以the error

Uncaught SyntaxError: Identifier 'x' has already been declared

不应该再出现,不管之前的变量初始化是否成功:

enter image description here

关于javascript - 声明变量和定义变量有区别吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54979906/

相关文章:

javascript - 将输入字符串分解为单个单词

JavaScript 范围问题,嵌套函数中的 var 访问未定义

javascript - 单击父菜单时如何将 + 更改为 -

javascript - array_contains 对象查询

javascript - 将变量放在双引号之间

variables - Lua 函数选择局部变量而不是全局变量

javascript - 如何解决无法读取react-native上未定义的属性 'push'?

javascript - 在 PHP 构建页面之前检测 PHP 中的 javascript

javascript - Node.js 加密和解密是文件大小加倍

php - 将表单验证值传递给 php