🔰destructuring array
JS ⟩ operator ⟩ assignment ⟩ destructuring ⟩ array
let [a, b] = [1, 2, 3]
let [a, ...rest] = array
💾 程式:replit
// array destructuring
let [a, b] = ["John", "Smith"]
let [a, b] = "John Smith".split(' ')
let [a, , c] = ["hi","what","hello"]; // ⭐ ignore elements
let [a, b, ...rest] = "abcdef" // ⭐ "rest" (array)
let [s, t = 0] = [1]; // ⭐ default values
let [
name = prompt('name?'), // ⭐ return value as default
surname = prompt('surname?')
] = ["Julius"];
// tricks
// ⭐ assign to object's properties
let user = {};
[user.name, user.surname] = "John Smith".split(' ');
// user = { name: 'John', surname: 'Smith' }
// ⭐ "swap" trick
let [p, q] = [1, 2];
[p, q] = [q, p]; // p=2, q=1
Last updated
Was this helpful?