ES6
ECMAScript就是JavaScript中的语法规范
ES6新增用法
let:
let特点:
1.没有变量提升,具有块级作用域
for (let i = 0; i < 5; i++) {
// var num = 4;
let num = 3;
console.log(num)
}
console.log(num);//num is not defined
function fnb() {
console.log(num);
let num = -1;//Cannot access 'num' before initialization 不能变量提升
} fnb();
2.不同重复同一个变量
for (let i = 0; i < 5; i++) {
var num = 4;
let num = 3;
console.log(num)//Identifier 'num' has already been declared
}
3.函数内不能用let重新声明函数的参数
function fn(name){
let name1 = '李四';
var name = name;
console.log(name1) //Identifier 'name' has already
}
fn('张三')
const
1、const声明变量(不能重复定义)
var num = 1;
const num = 2;
console.log(num)// Identifier 'num' has already been declared
2、变量不能提升
function fn1() {
console.log(num)
const num = 12;
} fn1();//Cannot access 'num' before initialization
3、具有块级作用域
for (var i = 0; i < 5; i++) {
const num = 10;
}
console.log(num)//num is not defined
4、const 是声明常量的,后面不能是变量,必须定义一个值
const num1 = "undefined";
const num2 = undefined;
const num3 = true;
console.log(num1, num2, num3)
5、常量不可修改
const num = 10;
num = 20;
console.log(num); //Assignment to constant variable
解构赋值
ES6允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构
数组的解构赋值
完全解构
let [a, b, c] = [1, 2, 3];
console.log(a, c, b)
不完全解构
let [a, b, c] = [1, 2]
console.log(a, b, c)//1,2,undefined
嵌套
let [a, b, [c, d]] = ["a", "b", ["C", "d"]]
console.log(a, b, c, d)
let [a = 1, b, c, d] = [10, 2, 3, 4]//可以给初始值(默认值),1被10给覆盖了
console.log(a, b, c, d)//10,2,3,4
let [a, b, c = 3] = [1, 2]
console.log(a, b, c)//1,2,3
交换两个变量的值
x = 1;
y = 2;
let [a, b] = [y, x]
console.log(a, b)
对象解构赋值(左右格式一样)
let { a, b, c } = { "a": 1, "b": 2, "c": 3 }
console.log(a, b, c)//1,2,3
var { a } = { "b": a }
console.log(a)//undefined
var { "b": a } = { "b": 2 }
console.log(a)//2
var { "a": b } = { "b": 2 }
console.log(b) //undefined
允许默认值
var { a, b = 2 } = { "a": 1, "b": 3 }
console.log(a, b)