Destructuring assignment

解構賦值可以將 array / object 的資料分散儲存到變數當中。

Array destructuring

// we have an array with the name and surname
let arr = ["Ilya", "Kantor"]
// destructuring assignment
let [firstName, surname] = arr;
alert(firstName); // Ilya
alert(surname);  // Kantor

// 解構賦值並沒有破壞原本的 array,而是將 array 值複製到變數當中。
let [firstName, surname] = "Ilya Kantor".split(' ');
// let [firstName, surname] = arr;
let firstName = arr[0];
let surname = arr[1];

// 不要的值可以用,代替
// second element is not needed
let [firstName, , title] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];
alert( title ); // Consul

// 可以使用在任何 iterable
let [a, b, c] = "abc"; // ["a", "b", "c"]
let [one, two, three] = new Set([1, 2, 3]);

// 變數可以是任何東西
let user = {};
[user.name, user.surname] = "Ilya Kantor".split(' ');
alert(user.name); // Ilya

// 可以使用在 key-value 上
let user = {
  name: "John",
  age: 30
};
// loop over keys-and-values
for (let [key, value] of Object.entries(user)) {
  alert(`${key}:${value}`); // name:John, then age:30
}

// 可以使用在 map
let user = new Map();
user.set("name", "John");
user.set("age", "30");
for (let [key, value] of user.entries()) {
  alert(`${key}:${value}`); // name:John, then age:30
}

The rest ‘…’

let [name1, name2, ...rest] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];

alert(name1); // Julius
alert(name2); // Caesar

// Note that type of `rest` is Array.
alert(rest[0]); // Consul
alert(rest[1]); // of the Roman Republic
alert(rest.length); // 2

Default values

// 變數多過 array,不會出現錯誤會儲存 undefined
let [firstName, surname] = [];
alert(firstName); // undefined
alert(surname); // undefined

// default values
let [name = "Guest", surname = "Anonymous"] = ["Julius"];
alert(name);    // Julius (from array)
alert(surname); // Anonymous (default used)

// runs only prompt for surname
let [name = prompt('name?'), surname = prompt('surname?')] = ["Julius"];
alert(name);    // Julius (from array)
alert(surname); // whatever prompt gets

Object destructuring

// 變數為 object 的 key
let {var1, var2} = {var1:, var2…}

let options = {
  title: "Menu",
  width: 100,
  height: 200
};
let {title, width, height} = options;
alert(title);  // Menu
alert(width);  // 100
alert(height); // 200

// 變數順序不影響
// changed the order of properties in let {...}
let {height, width, title} = { title: "Menu", height: 200, width: 100 }

// 變更變數名稱用:
let options = {
  title: "Menu",
  width: 100,
  height: 200
};
// { sourceProperty: targetVariable }
let {width: w, height: h, title} = options;

// width -> w
// height -> h
// title -> title

alert(title);  // Menu
alert(w);      // 100
alert(h);      // 200

// default value
let options = {
  title: "Menu"
};
let {width = 100, height = 200, title} = options;
alert(title);  // Menu
alert(width);  // 100
alert(height); // 200

// default value can be expression
let options = {
  title: "Menu"
};
let {width = prompt("width?"), title = prompt("title?")} = options;
alert(title);  // Menu
alert(width);  // (whatever you the result of prompt is)

// combine 
let options = {
  title: "Menu"
};
let {width: w = 100, height: h = 200, title} = options;
alert(title);  // Menu
alert(w);      // 100
alert(h);      // 200

The rest operator

let options = {
  title: "Menu",
  height: 200,
  width: 100
};

let {title, ...rest} = options;

// now title="Menu", rest={height: 200, width: 100}
alert(rest.height);  // 200
alert(rest.width);   // 100

Gotcha without let

let title, width, height;

// error in this line
{title, width, height} = {title: "Menu", width: 200, height: 100};

{
  // a code block
  let message = "Hello";
  // ...
  alert( message );
}

let title, width, height;

// okay now
({title, width, height} = {title: "Menu", width: 200, height: 100});

alert( title ); // Menu

Nested destructuring

let options = {
  size: {
    width: 100,
    height: 200
  },
  items: ["Cake", "Donut"],
  extra: true    // something extra that we will not destruct
};

// destructuring assignment on multiple lines for clarity
let {
  size: { // put size here
    width,
    height
  },
  items: [item1, item2], // assign items here
  title = "Menu" // not present in the object (default value is used)
} = options;

alert(title);  // Menu
alert(width);  // 100
alert(height); // 200
alert(item1);  // Cake
alert(item2);  // Donut

// take size as a whole into a variable, ignore the rest
let { size } = options;

Smart function parameters

// 要將多個值帶入函式中
function showMenu(title = "Untitled", width = 200, height = 100, items = []) {
  // ...
}

// 很醜
showMenu("My Menu", undefined, undefined, ["Item1", "Item2"])

// 解構賦值可以輕鬆達成
// we pass object to function
let options = {
  title: "My menu",
  items: ["Item1", "Item2"]
};
// ...and it immediately expands it to variables
function showMenu({title = "Untitled", width = 200, height = 100, items = []}) {
  // title, items – taken from options,
  // width, height – defaults used
  alert( `${title} ${width} ${height}` ); // My Menu 200 100
  alert( items ); // Item1, Item2
}
showMenu(options);

// 更複雜一些
let options = {
  title: "My menu",
  items: ["Item1", "Item2"]
};

function showMenu({
  title = "Untitled",
  width: w = 100,  // width goes to w
  height: h = 200, // height goes to h
  items: [item1, item2] // items first element goes to item1, second to item2
}) {
  alert( `${title} ${w} ${h}` ); // My Menu 100 200
  alert( item1 ); // Item1
  alert( item2 ); // Item2
}

showMenu(options);

// 要有帶入的參數不仁會出現錯誤
showMenu({});
showMenu(); // this would give an error

// 全部參數都有預設值可以不帶入值
// simplified parameters a bit for clarity
function showMenu({ title = "Menu", width = 100, height = 200 } = {}) {
  alert( `${title} ${width} ${height}` );
}
showMenu(); // Menu 100 200

Last updated