一.var和let
let
代码块内有效
不能重复定义
静态语言的感觉
二.const
let的不可变版
三.解构
1.数组解构
变量
let list = [1, 2, 3]; let [a, b, c] = list;
函数参数
function fun([a,b]:[number,string]) { console.log(a.toString()); console.log(b); }
部分解构
let list = [1, 2, 3, 4, 5]; let [a, ...list1] = list; //list1 [2,3,4,5]
忽略剩余
let [first] = [1, 2, 3, 4]; console.log(first); // outputs 1
跳过
let [, second, , fourth] = [1, 2, 3, 4];
2.对象解构
用{}表示对象
o = { a: "abc", b: 3, c: true }; let { a, b } = o;
剩余变量放到一个对象里
let o = { a: "abc", b: 3, c: true }; let { a, ...other } = o;
重命名
let { a: newName1, b: newName2 } = o; //相当于 let newName1 = o.a;
默认值
function fun(a = 10) { console.log(a); }
四.展开
赋值给一个数组
let first = [1, 2]; let second = [3, 4]; let bothPlus = [0, ...first, ...second, 5];
赋值对象
let defaults = { food: "spicy", price: "$$", ambiance: "noisy" }; let search = { ...defaults, food: "rich" };