语法错误:cons 声明中缺少 =

当 const 声明未在同一语句中给出值时(如 const RED_FLAG;),就会发生 JavaScript 异常 "cons 声明中缺少 ="。你需要提供一个 (const RED_FLAG = "#ff0")。

¥The JavaScript exception "missing = in const declaration" occurs when a const declaration was not given a value in the same statement (like const RED_FLAG;). You need to provide one (const RED_FLAG = "#ff0").

信息

¥Message

SyntaxError: Missing initializer in const declaration (V8-based)
SyntaxError: missing = in const declaration (Firefox)
SyntaxError: Unexpected token ';'. const declared variable 'x' must have an initializer. (Safari)

错误类型

¥Error type

SyntaxError

什么地方出了错?

¥What went wrong?

常量是程序在正常执行期间无法更改的值。它不能通过重新分配来更改,也不能重新声明。在 JavaScript 中,常量是使用 const 关键字声明的。需要常量的初始值设定项;也就是说,你必须在声明它的同一语句中指定它的值(这是有道理的,因为它以后不能更改)。

¥A constant is a value that cannot be altered by the program during normal execution. It cannot change through re-assignment, and it can't be redeclared. In JavaScript, constants are declared using the const keyword. An initializer for a constant is required; that is, you must specify its value in the same statement in which it's declared (which makes sense, given that it can't be changed later).

示例

¥Examples

缺少 const 初始值设定项

¥Missing const initializer

varlet 不同,你必须为 const 声明指定一个值。这会抛出:

¥Unlike var or let, you must specify a value for a const declaration. This throws:

js
const COLUMNS;
// SyntaxError: missing = in const declaration

修复错误

¥Fixing the error

有多种选项可以修复此错误。检查相关常量想要实现的目标。

¥There are multiple options to fix this error. Check what was intended to be achieved with the constant in question.

添加常量值

¥Adding a constant value

在声明常量的同一语句中指定常量值:

¥Specify the constant value in the same statement in which it's declared:

js
const COLUMNS = 80;

constlet 还是 var

¥const, let or var?

如果你不想声明常量,请不要使用 const。也许你打算使用 let 声明块作用域变量或使用 var 声明全局变量。两者都不需要初始值。

¥Do not use const if you weren't meaning to declare a constant. Maybe you meant to declare a block-scoped variable with let or global variable with var. Both don't require an initial value.

js
let columns;

也可以看看

¥See also