理解JavaScript的变量类型

在JavaScript中,我们可以通过3个关键字定义变量:var、let和const。这3个关键字有两点不同:可变性,与词法环境的关系。注意:var关键字从一开始就是JavaScript的一部分,而let与const是在ES6时加进来的。

变量可变性

如果通过变量的可变性来进行分类,那么可以将const放在一组,var和let放在一组。通过const定义的变量都不可变,也就是说通过const声明的变量的值只能设置一次。通过var或let声明的变量的值可以变更任意次数。

const变量

通过const声明的“变量”与普通变量类似,但在声明时需要写初始值,一旦声明完成之后,其值就无法更改。

const变量常用于两种目的:

1.不需要重新赋值的特殊变量

2.指向一个固定的值,例如球队人数的最大值,可通过const变量MAX_RONIN_COUNT来表示,而不是仅仅通过数字234来表示。这使得代码更加容易理解和维护。虽然代码里没有直接使用数字234,但是通过语义化的变量名MAX_RONIN_COUNT来表示,MAX_RONIN_COUNT的值只能指定一次。在其他情况下,由于在程序执行过程中不允许对const变量重新赋值,这可以避免代码发生不必要的变更,同时也为JavaScript引擎性能优化提供便利。

console.log("------------------const变量的行为-------------------");
//定义const变量,并验证该变量已被赋值
const firstConst = 'samurai';
if (firstConst === 'samurai') {
  console.log("FirstConst is a samurai.");
}

//试图为const变量重新赋值将抛出异常
try {
  firstConst = "ninja";
  console.log("Should not be here!");
} catch (e) {
  console.log("An exception has occurred!");
}

if (firstConst === 'samurai') {
  console.log("firstConst is still a samurai!");
}


//创建一个新的const变量,并赋值为空对象
const secondConst = {};

//我们不能再将一个全新的对象赋值给secondConst变量,但是可用对原有变量进行修改。
secondConst.weapon = "wakizashi";
if (secondConst.weapon === 'wakizashi') {
  console.log("We can add new properties!");
}

//const数组也一样
const thirdConst = [];
if (thirdConst.length === 0) {
  console.log("No items in our array.");
}
thirdConst.push("Yoshi");
if (thirdConst.length === 1) {
  console.log("The array has changed!");
}

 理解JavaScript的变量类型

 

这里首先定义了一个名为firstConst的const变量,并赋值为samurai,验证该变量已经被初始化,结果如预期:

const firstConst = 'samurai';

if (firstConst === 'samurai') {

console.log("FirstConst is a samurai.");

}

 

接着试图将一个全新的值ninja赋值给firstConst变量:

try {

firstConst = "ninja";

console.log("Should not be here!");

} catch (e) {

console.log("An exception has occurred!");

}

 

由于firstConst变量是静态变量,不允许重新赋值,因此,JavaScript引擎抛出异常。

console.log("Should not be here!");与console.log("An exception has occurred!");用于验证异常是否发生。

 

接下来,定义另一个const变量,并将其初始化为一个空对象:

const secondConst = {};

 

const变量的一个重要特性。我们不能将一个全新的值赋值给const变量。但是,我们可以修改const已有的对象。比如给已有的对象添加属性:

secondConst.weapon = "wakizashi";

if (secondConst.weapon === 'wakizashi') {

console.log("We can add new properties!");

}

 

//如果const变量指向一个数组,我们可以增加该数组的长度

const thirdConst = [];

if (thirdConst.length === 0) {

console.log("No items in our array.");

}

thirdConst.push("Yoshi");

if (thirdConst.length === 1) {

console.log("The array has changed!");

}

 

这就是const变量的全部特性。const变量并不复杂。你只需要记住const变量只能在声明的时候被初始化一次,之后再也不允许将全新的值赋值给const变量即可。但是,我们仍然可以修改const变量已经存在的值,只是不能重写const变量。

 

参考《JavaScript忍者秘籍》