本文介绍了声明变量和定义变量有区别吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着在控制台中一一写下以下几行

let x = y//抛出错误Uncaught ReferenceError: y is not defined"console.log(x)//抛出错误ReferenceError: x is not defined"让 x = 3;//给出错误未捕获的语法错误:标识符'x'已经被声明"x = 3//ReferenceError: x 未定义

现在的问题是一个变量如何未定义已声明同时存在.两者有什么区别吗.

解决方案

一个 letconst 变量只能声明一次 - 即也就是说,当你在一个作用域中有 let 时,你已经在那个作用域中声明了 ,并且不能在那个作用域中再次声明它.>

来自

I try writing the following lines in the console one by one

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

Now problem is that how can be a variable not defined and has been declared at the same time. Is there any difference between both.

解决方案

A let or const variable can only be declared once - that is, when you have let <variableName> in a scope, you have declared <variableName> in that scope, and cannot declare it again in that scope.

From the previously linked question:

You can't re-declare a variable that's already been declared, even though the attempted assignment during initialization threw an error.

After a variable has been initialized (for example, the let x runs), it can be assigned to. But just like you can't assign to a variable before its let initialization, you also can't assign to a variable later, when its initialization did not complete successfully:

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

Error:

Which is the same sort of thing that happens in the console when you try:

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 still has not been initialized, so the error is the same.

Encountering this sort of thing is pretty odd, though - you only see it in the console. In normal scripts, a thrown error will prevent further execution, and the fact that a variable name remains uninitialized forever is not something to worry about.


The above was an issue in earlier Chrome versions. But in Chrome 80+, re-declarations of let are now permitted, so the error

should no longer occur, regardless of whether the previous initialization of the variable succeeded or not:

这篇关于声明变量和定义变量有区别吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 18:57
查看更多