[...box.children] ๊ตฌ๋ฌธ์ HTMLCollection์ **๋ฐฐ์ด(Array)**๋ก ๋ณํํ๊ธฐ ์ํ ๋ฌธ๋ฒ์
๋๋ค.
ํ์ง๋ง ์ด๊ฒ์ HTMLCollection์๋ง ๊ตญํ๋์ง ์๊ณ , ๋ชจ๋ ์ดํฐ๋ฌ๋ธ(Iterable) ๊ฐ์ฒด์ ์ ์ฉํ ์ ์์ต๋๋ค.
1๏ธโฃ [...box.children]์ ์๋ฏธ
const arr = [...box.children];
box.childrenโ HTMLCollection(์ ์ฌ ๋ฐฐ์ด ๊ฐ์ฒด)...(์คํ๋ ๋ ์ฐ์ฐ์) โ ์ดํฐ๋ฌ๋ธ์ ํผ์ณ์ ์๋ก์ด ๋ฐฐ์ด๋ก ๋ณต์ฌ- ๊ฒฐ๊ณผ โ ์ค์ ๋ฐฐ์ด(Array)
์ฆ, ๋ด๋ถ์ ์ผ๋ก๋ ์ด๋ ๊ฒ ๋์ํฉ๋๋ค ๐
โ
box.children์์ ์์๋ค์ ํ๋์ฉ ๊บผ๋ด์ ๋ฐฐ์ด์ ๋ด์๋ผ.โ
2๏ธโฃ HTMLCollection์ด๋?
HTMLCollection์ DOM ์์๋ค์ ์งํฉ์ ๋ํ๋ด๋ ์ ์ฌ ๋ฐฐ์ด ๊ฐ์ฒด์ ๋๋ค.
<div class="box">
<p>์ฒซ ๋ฒ์งธ</p>
<p>๋ ๋ฒ์งธ</p>
<p>์ธ ๋ฒ์งธ</p>
</div>
const box = document.querySelector(".box");
console.log(box.children);
// HTMLCollection(3) [<p>, <p>, <p>]
๐ก HTMLCollection์
forEach,map,filter๊ฐ์ ๋ฐฐ์ด ๋ฉ์๋๋ฅผ ๋ฐ๋ก ์ฌ์ฉํ ์ ์์ต๋๋ค.
๊ทธ๋์ ๋ค์๊ณผ ๊ฐ์ด ๋ฐฐ์ด๋ก ๋ณํํด์ผ ํฉ๋๋ค ๐
[...box.children].forEach(el => console.log(el.textContent));
3๏ธโฃ [...iterable]์ HTMLCollection๋ฟ ์๋๋ผ โ๋ชจ๋ ์ดํฐ๋ฌ๋ธโ์ ์ฌ์ฉ ๊ฐ๋ฅ
์คํ๋ ๋ ๋ฌธ๋ฒ(...)์ **์ดํฐ๋ฌ๋ธ(Iterable)**์ ๋์์ผ๋ก ๋์ํฉ๋๋ค.
์ดํฐ๋ฌ๋ธ์ด๋ for...of๋ก ์ํ ๊ฐ๋ฅํ ๊ฐ์ฒด๋ฅผ ๋งํฉ๋๋ค.
โ ์คํ๋ ๋ ๊ฐ๋ฅํ ๋ํ ์ดํฐ๋ฌ๋ธ
| ์ดํฐ๋ฌ๋ธ ๊ฐ์ฒด | ์ค๋ช | ์์ |
|---|---|---|
| Array | ๊ธฐ๋ณธ ๋ฐฐ์ด | [...[1, 2, 3]] โ [1, 2, 3] |
| String | ๋ฌธ์์ด | [...'ABC'] โ ['A', 'B', 'C'] |
| Set | ์ค๋ณต ์๋ ์งํฉ | [...new Set([1, 2, 2, 3])] โ [1, 2, 3] |
| Map | ํค-๊ฐ ์์ ์งํฉ | [...new Map([['a',1],['b',2]])] โ [ ['a',1], ['b',2] ] |
| NodeList | querySelectorAll() ๋ฐํ๊ฐ |
[...document.querySelectorAll('p')] |
| HTMLCollection | children, getElementsByTagName() ๋ฑ |
[...box.children] |
4๏ธโฃ โ ์คํ๋ ๋๊ฐ ๋ถ๊ฐ๋ฅํ ๊ฒฝ์ฐ (๋น์ดํฐ๋ฌ๋ธ)
์ผ๋ฐ ๊ฐ์ฒด(Object)๋ ๊ธฐ๋ณธ์ ์ผ๋ก ์ดํฐ๋ฌ๋ธ์ด ์๋๋๋ค.
const obj = { a: 1, b: 2 };
const arr = [...obj]; // โ TypeError: obj is not iterable
โ ํ์ง๋ง ๋ณํ ํ์ ๊ฐ๋ฅ!
๊ฐ์ฒด๋ฅผ ๋ฐฐ์ด๋ก ๋ณํํ๋ฉด ์คํ๋ ๋ ์ฌ์ฉ์ด ๊ฐ๋ฅํฉ๋๋ค ๐
[...Object.entries(obj)] // โ
[['a',1], ['b',2]]
[...Object.keys(obj)] // โ
['a','b']
[...Object.values(obj)] // โ
[1,2]
5๏ธโฃ ์์ฝ ์ ๋ฆฌ
| ํ์ | [...something] ๊ฐ๋ฅ ์ฌ๋ถ |
์ด์ |
|---|---|---|
| Array | โ | ์๋ ์ดํฐ๋ฌ๋ธ |
| String | โ | ํ ๊ธ์์ฉ ์ํ ๊ฐ๋ฅ |
| Set / Map | โ | ๋ฐ๋ณต ๊ฐ๋ฅํ ๊ตฌ์กฐ |
| NodeList / HTMLCollection | โ | DOM ์ํ ๊ฐ๋ฅ |
| Object (์ผ๋ฐ ๊ฐ์ฒด) | โ | ๊ธฐ๋ณธ์ ์ผ๋ก ์ดํฐ๋ฌ๋ธ ์๋ |
๐ ๋ง๋ฌด๋ฆฌ
[...box.children]์ HTMLCollection์ ๋ฐฐ์ด๋ก ๋ณํํ๋ ์ฝ๋์ง๋ง,
๋ณธ์ง์ ์ผ๋ก๋ **โ์ดํฐ๋ฌ๋ธ์ด๋ผ๋ฉด ๋ชจ๋ ํผ์น ์ ์๋คโ**๋ ๋ป์ ๋๋ค.
์ฆ, [...iterable]์
๋ฐฐ์ด๋ก ๋ณํํ๊ฑฐ๋ ๋ณต์ฌํ ๋ ์ฌ์ฉํ๋ ๊ฐ์ฅ ๋ฒ์ฉ์ ์ธ ๋ฌธ๋ฒ์
๋๋ค ๐
๋ต๊ธ ๋จ๊ธฐ๊ธฐ