🔰object destructuring
JS ⟩ operator ⟩ assignment ⟩ destructuring ⟩ object
let opts = { title: "Menu", width: 100, height: 200};
// ⭐ object destructuring
let {title, width, noSuchThing} = opts; // noSuchThing = undefined❗
// ⭐ rename variables
let {title: t, width: w} = opts; // t = "Menu", w = 100
// ⭐ default values (could be function values❗)
let {width: w2 = 100, title: t2} = opts; // t2 = "Menu", w2 = 100
// ⭐ the "rest" object
let {title: t3, ...rest} = opts; // rest = {width: 100, height: 200}
👉 replit
replit ⟩ object destructuring ⟩ catch
// ⭐️ 可先宣告變數,再 destructuring,但要「小心」❗
let t, w, h;
// ------------------ 🧨 there's a catch❗ --------------------
// ⛔ SyntaxError: Unexpected token '='
// {t, w, h} = opts;
// ^^^^^^^^^ <------------ JS sees this as a "code block"❗
// ------------------------------------------------------------
// ✅ wrap it in "parentheses", now it's OK.
({title: t, width: w, height: h} = opts);
// ^ ^
Last updated
Was this helpful?