1 聲明變量的關(guān)鍵字
let a = 1;
const b = 3;
console.log(a,b);//1 3
2 let的用法
- 塊作用域內(nèi)有效
全局作用域畏吓,函數(shù)作用域墨状。另外for循環(huán)的,函數(shù)的圓括號也是作用域菲饼。
for(let i = 0;i < 5;i++){
}
console.log(i);//i is not defined
let x = 5;
function add(x,y=x){
return x+y;
}
console.log(add(3));//6
- 變量不提升
console.log(a);//報(bào)錯:Cannot access 'a' before initialization
let a = 1;
- 不可重復(fù)聲明
let a = 1;
let a = 2;//報(bào)錯:Identifier 'a' has already been declared
3 const的用法
簡單用法如下
const PI = 3.14;
console.log(PI);//3.14
const用來聲明一個常量肾砂,在遵循所有l(wèi)et關(guān)鍵字的法則之外,還需注意:
- 聲明時必須賦值
const PI;
PI = 3.14;
console.log(PI);
//報(bào)錯:Missing initializer in const declaration 語法不完整宏悦,沒有在聲明時賦值
- 如果賦值為基本數(shù)據(jù)類型镐确,那么值為只讀,不可變
const PI=3.14;
PI = 3.1415926;
console.log(PI);
//報(bào)錯:Assignment to constant variable 禁止后續(xù)給常量賦值
- 如果賦值為引用類型值饼煞,那么屬性可變
const a = {age:18};
a.name = 'zhangsan';
delete a.age;
console.log(a);//{name:'zhangsan'}