const

const 声明声明块范围的局部变量。常量的值无法通过使用 赋值运算符 重新分配来更改,但如果常量是 object,则可以添加、更新或删除其属性。

¥The const declaration declares block-scoped local variables. The value of a constant can't be changed through reassignment using the assignment operator, but if a constant is an object, its properties can be added, updated, or removed.

Try it

语法

¥Syntax

js
const name1 = value1;
const name1 = value1, name2 = value2;
const name1 = value1, name2 = value2, /* …, */ nameN = valueN;
nameN

要声明的变量的名称。每个都必须是合法的 JavaScript identifier解构结合模式

valueN

变量的初始值。它可以是任何合法的表达式。

描述

¥Description

const 声明与 let 非常相似:

¥The const declaration is very similar to let:

  • const 声明的作用域为块和函数。
  • const 声明只能在到达声明位置后才能访问(参见 颞死区)。因此,const 声明通常被视为 non-hoisted
  • 当在脚本的顶层声明时,const 声明不会在 globalThis 上创建属性。
  • const 声明不能被同一范围内的任何其他声明成为 redeclared
  • const 开始 声明,而不是声明。这意味着你不能使用单独的 const 声明作为块的主体(这是有道理的,因为无法访问该变量)。
    js
    if (true) const a = 1; // SyntaxError: Lexical declaration cannot appear in a single-statement context
    

需要常量的初始值设定项。你必须在同一声明中指定其值。(这是有道理的,因为以后无法更改。)

¥An initializer for a constant is required. You must specify its value in the same declaration. (This makes sense, given that it can't be changed later.)

js
const FOO; // SyntaxError: Missing initializer in const declaration

const 声明创建对值的不可变引用。这并不意味着它所保存的值是不可变的 - 只是变量标识符不能被重新分配。例如,在内容是对象的情况下,这意味着可以改变对象的内容(例如,其属性)。你应该将 const 声明理解为 "创建一个身份保持不变的变量",而不是 "其值保持不变",或者“创建不可变的 bindings”,而不是 "不可变的值"。

¥The const declaration creates an immutable reference to a value. It does not mean the value it holds is immutable — just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered. You should understand const declarations as "create a variable whose identity remains constant", not "whose value remains constant" — or, "create immutable bindings", not "immutable values".

许多风格指南(包括 MDN 的)建议在变量未在其作用域中重新分配时使用 const 而不是 let。这使得意图变得清晰:变量的类型(或值,在原语的情况下)永远不会改变。其他人可能更喜欢 let 作为突变的非基元。

¥Many style guides (including MDN's) recommend using const over let whenever a variable is not reassigned in its scope. This makes the intent clear that a variable's type (or value, in the case of a primitive) can never change. Others may prefer let for non-primitives that are mutated.

const 关键字后面的列表称为 binding 列表,并以逗号分隔,其中逗号不是 逗号运算符= 符号不是 赋值运算符。后面变量的初始化程序可以引用列表中前面的变量。

¥The list that follows the const keyword is called a binding list and is separated by commas, where the commas are not comma operators and the = signs are not assignment operators. Initializers of later variables can refer to earlier variables in the list.

示例

¥Examples

基本常量用法

¥Basic const usage

常量可以用大写或小写来声明,但常见的约定是使用全大写字母,特别是对于基元,因为它们确实是不可变的。

¥Constants can be declared with uppercase or lowercase, but a common convention is to use all-uppercase letters, especially for primitives because they are truly immutable.

js
// define MY_FAV as a constant and give it the value 7
const MY_FAV = 7;

console.log("my favorite number is: " + MY_FAV);
js
// Re-assigning to a constant variable throws an error
MY_FAV = 20; // TypeError: Assignment to constant variable

// Redeclaring a constant throws an error
const MY_FAV = 20; // SyntaxError: Identifier 'MY_FAV' has already been declared
var MY_FAV = 20; // SyntaxError: Identifier 'MY_FAV' has already been declared
let MY_FAV = 20; // SyntaxError: Identifier 'MY_FAV' has already been declared

块作用域

¥Block scoping

请务必注意块作用域的性质。

¥It's important to note the nature of block scoping.

js
const MY_FAV = 7;

if (MY_FAV === 7) {
  // This is fine because it's in a new block scope
  const MY_FAV = 20;
  console.log(MY_FAV); // 20

  // var declarations are not scoped to blocks so this throws an error
  var MY_FAV = 20; // SyntaxError: Identifier 'MY_FAV' has already been declared
}

console.log(MY_FAV); // 7

对象和数组中的 const

¥const in objects and arrays

const 也适用于对象和数组。尝试覆盖该对象会引发错误 "给常量变量赋值"。

¥const also works on objects and arrays. Attempting to overwrite the object throws an error "Assignment to constant variable".

js
const MY_OBJECT = { key: "value" };
MY_OBJECT = { OTHER_KEY: "value" };

但是,对象键不受保护,因此执行以下语句没有问题。

¥However, object keys are not protected, so the following statement is executed without problem.

js
MY_OBJECT.key = "otherValue";

你需要使用 Object.freeze() 来使对象不可变。

¥You would need to use Object.freeze() to make an object immutable.

这同样适用于数组。将新数组分配给变量会引发错误 "给常量变量赋值"。

¥The same applies to arrays. Assigning a new array to the variable throws an error "Assignment to constant variable".

js
const MY_ARRAY = [];
MY_ARRAY = ["B"];

尽管如此,仍然可以将项目推入数组并从而改变它。

¥Still, it's possible to push items into the array and thus mutate it.

js
MY_ARRAY.push("A"); // ["A"]

带有解构的声明

¥Declaration with destructuring

每个 = 的左侧也可以是装订图案。这允许一次创建多个变量。

¥The left-hand side of each = can also be a binding pattern. This allows creating multiple variables at once.

js
const result = /(a+)(b+)(c+)/.exec("aaabcc");
const [, a, b, c] = result;
console.log(a, b, c); // "aaa" "b" "cc"

欲了解更多信息,请参阅 解构赋值

¥For more information, see Destructuring assignment.

规范

Specification
ECMAScript Language Specification
# sec-let-and-const-declarations

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看