一、let
1.1 let声明变量的格式
//let声明变量格式
let a; //单纯声明1个
let b, c, d; //单纯声明多个
let e = 100; //赋初始值
let f = 520,
g = 321,
h = []; //声明多个并赋初始值
1.2 let声明变量的新特性
①变量不能重复声明
let star = "yello";
let star = "blue";
②块级作用域(变量只在代码块里面【if、else、while、for】有效,代码块外面无效)
{
let girl = "小红";
}
console.log(girl);
③不存在变量提升
console.log(song); //输出undefined,并不会报错
var song = "告白气球";
console.log(song); // Cannot access 'song' before initialization
let song = "告白气球";
④不影响作用域链(虽说是块级作用域,但不影响作用域链的效果)
{
let school = "尚硅谷";
function fn() {
console.log(school); //输出尚硅谷
}
fn();
}
函数作用域下面没有school变量,它会向上一级作用域中找school变量
二、const定义常量(值不能修改的量称之为常量)
2.1 声明时一定要赋初始值
const a; //Missing initializer in const declaration
2.2一般常量使用大写(潜规则,小写也不会报错)
2.3常量的值不能修改
const A = a;
A = b; //Assignment to constant variable.
2.4块级作用域
2.5 对于数组和对象的元素修改,不算做对常量的修改,不会报错
const TEAM = ["UZI", "MXLG", "MING", "LETME"];
TEAM.push("Meiko");
数组和对象的声明用const比较稳妥