JS 解構賦值

解構賦值

允許按照一定模式,從數組和對象中提取值,並對變量進行賦值

數組解構:順序對應

  • 需要一一對應,不需要的也要留出空位
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);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章