示例:使用常量
// program to include constants
const a = 5;
console.log(a);
// constants are block-scoped
{
const a = 50;
console.log(a);
}
console.log(a);
const arr = ['work', 'exercise', 'eat'];
console.log(arr);
// add elements to arr array
arr[3] = 'hello';
console.log(arr);
// the following code gives error
// changing the value of a throws an error
// uncomment to verify
// a = 8;
// throws an error
// const x;
输出
5 50 5 ["work", "exercise", "eat"] ["work", "exercise", "eat", "hello"]
JavaScript ES6 引入了 const 关键字来处理常量。const
表示对值的引用是恒定的,不能改变。
例如,
const a = 5;
a = 44; // throws an error
常量是块级作用域的。因此,在块内定义的变量与块外定义的变量代表的值不同。例如,
{
const a = 50;
console.log(a); // 50
}
console.log(a); // 5
数组 arr 的值被更改并添加了一个新元素。在 数组中,值是可以更改的。但是,数组引用不能更改。例如,
const arr = ['work', 'exercise', 'eat'];
arr[3] = 'hello';
此外,常量必须初始化。你不能仅仅声明一个常量。例如,
const x;
// SyntaxError: const declared variable 'x' must have an initializer.