JS 中Missing initializer in const declaration错误
“Missing initializer in const declaration”错误发生在使用 const
声明变量时,但其值未在同一行上初始化。 要解决该错误,请在声明它的同一行上初始化该变量,例如 const num = 30;
。
下面是发上上述错误的示例代码
// ⛔️ Missing initializer in const declaration
const country;
// ⛔️ Missing initializer in const declaration
const age;
age = 30;
我们使用 const
关键字声明了一个变量,但是,我们没有初始化它的值,这导致了错误。
使用
const
声明的变量不能重新分配,因此我们必须在声明时设置它们的值。
如果我们需要声明一个可以重新分配的变量,请改用 let
语句。
// ✅ let = can be reassigned
let country;
country = 'Chile';
// ✅ const = Set value upon declaration
const age = 30;
如果我们无法找出错误发生的位置,请查看浏览器的控制台选项卡或 Node.js 终端中的错误消息。 错误信息应该显示发生错误的文件和具体的行。
可以重新分配使用 let 语句声明的变量。 但是,它们不能重新声明。
let country;
// ⛔️ Identifier 'country' has already been declared
let country = 'Chile';
我们试图重新声明 country
变量并得到一个错误。 相反,在重新分配使用 let 声明的变量时省略 let 关键字。
如果我们不需要重新分配变量,请使用 const
关键字并在声明变量时设置其值。
// ✅ Works
const country = 'Chile';
// ⛔️ Error: Assignment to constant variable
country = 'Brazil';
不能重新分配使用
const
关键字声明的变量。
使用 const
可以让代码的读者知道以后不会重新分配此变量。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
将 Pandas DataFrame 转换为 JSON
发布时间:2024/04/21 浏览次数:153 分类:Python
-
本教程演示了如何将 Pandas DataFrame 转换为 JSON 字符串。
在 Pandas 中加载 JSON 文件
发布时间:2024/04/21 浏览次数:105 分类:Python
-
本教程介绍了我们如何使用 pandas.read_json()方法将一个 JSON 文件加载到 Pandas DataFrame 中。
将 JSON 转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:135 分类:Python
-
本教程演示了如何使用 json_normalize()和 read_json()将 JSON 字符串转换为 Pandas DataFrame。
从 JavaScript 中的 JSON 对象获取值
发布时间:2024/03/22 浏览次数:177 分类:JavaScript
-
通过 JSON.parse() 方法访问 JavaScript 中的 JSON 对象和数组可以有多种做法。可以使用点(.) 操作或括号对([]) 访问它。