我尝试在控制台中一行一行地编写以下行
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 let
或 const
变量只能声明一次——也就是说,当你有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
不应该再出现,不管之前的变量初始化是否成功:
关于javascript - 声明变量和定义变量有区别吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54979906/