解構賦值
允許按照一定模式,從數組和對象中提取值,並對變量進行賦值
數組解構:順序對應
- 需要一一對應,不需要的也要留出空位
let [a, b, c] = [1, 2, 3];
等同於
let arr = [1, 2, 3];
let a = arr[0];
let b = arr[1];
let c = arr[2];
對象解構:key值對應
- 左側中變量的名稱必須是右側對象中存在的key
- 解構的順序不需要對應
let { foo, bar } = { foo: "aaa", bar: "bbb" };
解構賦值:別名
let { left: L, top: T } = { left: 100, top: 200 };
console.log(L, T);
結果爲:
100 200
多重解構
let { foo: [a, b] } = { foo: [10, 20], bar: 'bbb' };
console.log(a, b);
結果爲:
10 20
例子:
var left = getComputedStyle(document.body).left;
var top = getComputedStyle(document.body).top;
var width = getComputedStyle(document.body).width;
var height = getComputedStyle(document.body).height;
可簡寫爲:
let { left: L, top: T, width: W, height: H } = getComputedStyle(document.body);