ES6基礎之——恆量const

使用const能夠去聲明一個衡量,這樣就不可以給這個衡量去從新分配一個新的值

 

例子:
const fruit ="apple";
console.log(fruit);

const fruit ="lemon";
console.log(fruit);

 

在控制檯上會報語法錯誤:
Uncaught SyntaxError: Identifier 'fruit' has already benn declared at <anonymous>:1:1

 

注意:const限制的是給const分配值的動做,並非限制衡量裏面的值
 
例子:
const fruit =[];
fruit.push('apple');
fruit.push('lemon');
console.log(fruit); //[apple,lemon]

 

若是從新給fruit分配一個值:
fruit=[];
console.log(fruit); //Uncaught SyntaxError: Assignment to constant variable.

 

這就是由於咱們從新分配了fruit的值
相關文章
相關標籤/搜索