🔰destructuring iterable
JS ⟩ operator ⟩ assignment ⟩ destructuring ⟩ iterable
let [a, ...rest] = "abc" // rest = ['b', 'c']
for (const [i, value] of arr.entries()) { ... }
💾 程式:replit
// ⭐ works with any "iterable"
let [one, two, three] = new Set([1, 2, 3]); // 1, 2, 3
// ⭐ "rest" (array)
let [a, b, ...rest] = "abcdef" // a="a", b="b", rest=[ 'c', 'd', 'e', 'f' ]
// ----------------- ⭐ loop over key-value pairs -----------------
// 🔸 1. iterate over object properties
// use `Object.entries()` for ordinary objects
for (let [key, value] of Object.entries(obj)) {
log(`${key}: ${value}`); // "name: John", "surname: Smith"
}
// 🔸 2. iterate over `Map`
for (let [key, value] of aMap) {
log(`${key}: ${value}`); // "name: John", "age: 30"
}
Last updated
Was this helpful?