JavaScript 常量
JavaScript 常量(constants)是其值在整个程序执行过程中保持不变的变量。您可以使用 const 关键字声明常量。
const 关键字是在 ES6 版本的 JavaScript 中通过 let 关键字引入的。const 关键字用于定义具有常量引用的变量。使用 const 定义的变量不能重新声明、重新分配。const 声明具有块和函数范围。
JavaScript 常量声明
如果使用 const 关键字声明变量,则始终需要在声明时分配一个值。
在任何情况下,如果不进行初始化,都不能使用 const 关键字声明变量。
无法重新分配
您无法更新使用 const 关键字声明了的变量值。
const y = 20;
y = 40; // 这是不可能的
块范围
使用 const 关键字声明的 JavaScript 变量具有块范围。这意味着在 blcok 之外,相同的变量被视为不同变量。
在下面的示例中,在块中声明的 x 与在 blcok 外部声明的 x 不同。所以我们可以在区块外部 重新声明 相同变量
{
const x = "john";
}
const x = "Doe"
但是我们不能在同一个块中重新声明 const 变量 。
{
const x = "john";
const x = "Doe" // incorrect
}
JavaScript 中的常量数组和对象
我们可以使用 const 关键字声明数组和对象,但数组和对象声明中有一个小转折。
带有 const 关键字的变量保留常量引用,但不保留常量值。因此,您可以更新使用 const 关键字声明的相同数组或对象,但不能将新数组或对象的引用重新分配给常量变量。
示例(常量数组)
在下面的示例中,我们使用 const 关键字定义了名为 'arr' 的数组。之后,我们在第 0 个索引处更新数组元素,并在数组末尾插入 'fence' 字符串。
在输出中,您可以观察到它打印更新的数组。
<html>
<head>
<title> Consant Arrays </title>
</head>
<body>
<script>
// Defining the constant array
const arr = ["door", "window", "roof", "wall"];
// Updating arr[0]
arr[0] = "gate";
// Inserting an element to the array
arr.push("fence");
//arr = ["table", "chair"] // reassiging array will cause error.
// Printing the array
document.write(arr);
</script>
</body>
</html>
当您执行上述代码时,它将产生以下结果 -
示例(常量对象)
在下面的示例中,我们使用 const 关键字创建了 'obj' 对象。接下来,我们更新对象的 'animal' 属性,并在对象中插入 'legs' 属性。在输出中,代码将打印更新的对象。
<html>
<head>
<title> Constant Objects </title>
</head>
<body>
<script>
// Defining the constant object
const obj = {
animal: "Lion",
color: "Yellow",
};
// Changing animal name
obj.animal = "Tiger";
// Inserting legs property
obj.legs = 4;
// Printing the object
document.write(JSON.stringify(obj));
// obj = { name: "cow" } // This is not possible
</script>
</body>
</html>
它将产生以下结果 -
因此,我们不能更改对使用 const 关键字声明的变量(数组和对象)的引用,但会更新元素和属性。
无 const 提升
使用 const 关键字定义的变量不会提升到代码顶部。
在下面的示例中,在定义 const 变量 x 之前对其进行访问。这将导致错误。我们可以使用 try-catch 语句捕获错误。
<html>
<body>
<script>
document.write(x);
const x = 10;
</script>
</body>
</html>
以下是使用 const 关键字声明的变量的一些其他属性。
- 块范围。
- 不能在同一范围内重新声明。
- 使用 const 关键字声明的变量不能提升到代码顶部。
- 常量变量值是一个基元值。
var、let 和 const 之间的区别
我们给出了使用 var、let 和 const 关键字声明的变量之间的比较表。
比较基础 | var | let | const |
---|---|---|---|
范围 | 函数 | 块 | 块 |
悬挂 | Yes | No | No |
分配 | Yes | Yes | No |
重新声明 | Yes | No | No |
绑定此 | Yes | No | No |
你应该在 var、let 和 const 中使用哪个?
- 对于块范围,您应该使用 let 关键字。
- 如果需要将常量引用分配给任何值,请使用 const 关键字。
- 当你需要在任何特定块内定义变量时,如循环、'if 语句' 等,并且需要在块外部但在函数内部访问,你可以使用 var 关键字。
- 但是,您可以使用 any 关键字来定义全局变量。
- 重新声明变量不是一种好的做法。因此,您应该避免使用它,但如有必要,您可以使用 var 关键字。