迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 >

JS 中Missing initializer in const declaration错误

作者:迹忆客 最近更新:2022/12/21 浏览次数:

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;

JS 中Missing initializer in const declaration

我们使用 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';

JavaScript Identifier 'country' has already been declared

我们试图重新声明 country 变量并得到一个错误。 相反,在重新分配使用 let 声明的变量时省略 let 关键字。

如果我们不需要重新分配变量,请使用 const 关键字并在声明变量时设置其值。

// ✅ Works
const country = 'Chile';

// ⛔️ Error: Assignment to constant variable
country = 'Brazil';

不能重新分配使用 const 关键字声明的变量。

使用 const 可以让代码的读者知道以后不会重新分配此变量。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

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 中加载 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。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便