๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๋…์„œ ๋ชฉ๋ก/๋ชจ๋”ฅ๋‹ค Modern JS Deep Dive

[๋ชจ๋”ฅ๋‹ค] 36์žฅ ๋””์ŠคํŠธ๋Ÿญ์ฒ˜๋ง ํ• ๋‹น

728x90

 

 

๋””์ŠคํŠธ๋Ÿญ์ฒ˜๋ง ํ• ๋‹น (๊ตฌ์กฐ ๋ถ„ํ•ด ํ• ๋‹น)
๊ตฌ์กฐํ™”๋œ ๋ฐฐ์—ด๊ณผ ๊ฐ™์€ ์ดํ„ฐ๋Ÿฌ๋ธ” ๋˜๋Š” ๊ฐ์ฒด๋ฅผ Destructuring = ๋น„๊ตฌ์กฐํ™”, ๊ตฌ์กฐ ํŒŒ๊ดด ํ•˜์—ฌ 1๊ฐœ ์ด์ƒ์˜ ๋ณ€์ˆ˜์— ๊ฐœ๋ณ„์ ์œผ๋กœ ํ• ๋‹นํ•˜๋Š” ๊ฒƒ์„ ๋งํ•œ๋‹ค.

 

 

๐Ÿฒ 36.1 ๋ฐฐ์—ด ๋””์ŠคํŠธ๋Ÿญ์ฒ˜๋ง ํ• ๋‹น

 

๋ฐฐ์—ด ๋””์ŠคํŠธ๋Ÿญ์ฒ˜๋ง ํ• ๋‹น์˜ ๋Œ€์ƒ(ํ• ๋‹น๋ฌธ์˜ ์šฐ๋ณ€)์€ ์ดํ„ฐ๋Ÿฌ๋ธ”์ด์—ฌ์•ผ ํ•˜๋ฉฐ, ํ• ๋‹น ๊ธฐ์ค€์€ ๋ฐฐ์—ด์˜ ์ธ๋ฑ์Šค๋‹ค. 

์ฆ‰, ์ˆœ์„œ๋Œ€๋กœ ํ• ๋‹น๋œ๋‹ค.

const arr = [1, 2, 3];

const [one, two, tree] = arr;

console.log(one, two, three); // 1, 2, 3

 

const [x, y] = [1, 2];

 

์šฐ๋ณ€์— ์ดํ„ฐ๋Ÿฌ๋ธ” ํ• ๋‹น์„ ํ•˜์ง€ ์•Š์œผ๋ฉด ์˜ค๋ฅ˜๋‚จ. 

 

์š”์†Œ ๊ฐœ์ˆ˜๊ฐ€ ๋ฐ˜๋“œ์‹œ ์ผ์น˜ํ•  ํ•„์š”๋Š” ์—†๋‹ค.

const [a, b] = [1];
console.log(a, b) // 1 undefined

 

๊ธฐ๋ณธ๊ฐ’๋ณด๋‹ค ํ• ๋‹น๋œ ๊ฐ’์ด ์šฐ์„ ๋œ๋‹ค.

const [a, b, c = 3] = [1, 2, 10];
console.log(a, b, c) //1 2 10

๊ธฐ๋ณธ๊ฐ’ 3์ด ์•„๋‹Œ ํ• ๋‹น๋œ 10์ด ๋จ.

 

 

 

 

 

 

๐Ÿฒ 36.2 ๊ฐ์ฒด ๋””์ŠคํŠธ๋Ÿญ์ฒ˜๋ง ํ• ๋‹น

 

๊ฐ ํ”„๋กœํผํ‹ฐ๋ฅผ ๊ฐ์ฒด๋กœ๋ถ€ํ„ฐ ๋””์ŠคํŠธ๋Ÿญ์ณ๋ง ํ•˜์—ฌ ๋ณ€์ˆ˜์— ํ• ๋‹นํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” ํ”„๋กœํผํ‹ฐ ํ‚ค๋ฅผ ์‚ฌ์šฉํ•ด์•ผํ•œ๋‹ค.

๊ฐ์ฒด ๋””์ŠคํŠธ๋Ÿญ์ฒ˜๋ง ํ• ๋‹น ๊ธฐ์ค€์€ ํ”„๋กœํผํ‹ฐ ํ‚ค๋‹ค. 

์ฆ‰, ์ˆœ์„œ๋Š” ์˜๋ฏธ๊ฐ€ ์—†์œผ๋ฉฐ, ์„ ์–ธ๋œ ๋ณ€์ˆ˜ ์ด๋ฆ„๊ณผ ํ”„๋กœํผํ‹ฐ ํ‚ค๊ฐ€ ์ผ์น˜ํ•˜๋ฉด ํ• ๋‹น๋œ๋‹ค.

 

(ํ .. ์–ด๋””์„œ ๋งŽ์ด ๋“ค์–ด๋ดค๋Š”๋ฐ)

 

const user = { firstName: 'San', lastName: "ta" };

const firstName = user.firstName;
const lastName = user.lastName;

=> ์ด ๋ถ€๋ถ„์„

const { firstName, lastName } = user;

์ด๋ ‡๊ฒŒ ์จ์ค˜๋„ ๋จ.

console.log(firstName, lastName);
//San ta

 

 

๊ฐ์ฒด์˜ ํ”„๋กœํผํ‹ฐ์™€ ๋‹ค๋ฅธ ์ด๋ฆ„์œผ๋กœ ๊ฐ’์„ ํ• ๋‹น๋ฐ›์œผ๋ ค๋ฉด ๋ณ€์ˆ˜๋ฅผ ์•„๋ž˜์™€ ๊ฐ™์ด ์„ ์–ธํ•œ๋‹ค.

const user = { firstName: 'Hi', lastName: "Hello" };

const { lastName: ln, firstName: fn } = user;
console.log(fn, ln);
//Hi Hello

=> firstName, lastName ๋ณ€์ˆ˜ ์ด๋ฆ„ ์‚ฌ์šฉํ•˜๋ คํ•˜๋ฉด ์—๋Ÿฌ๋‚จ.

 

๐Ÿ“Œ ๊ฐ์ฒด ๋””์ŠคํŠธ๋Ÿญ์ฒ˜๋ง ํ• ๋‹น์€ ๊ฐ์ฒด์—์„œ ํ•„์š”ํ•œ ํ”„๋กœํผํ‹ฐ๊ฐ’๋งŒ ์ถ”์ถœํ•˜์—ฌ ๋ณ€์ˆ˜์— ํ• ๋‹นํ•˜๊ณ  ์‹ถ์„ ๋•Œ ์œ ์šฉํ•˜๋‹ค.

const str = "hello";

const { length } = str;
console.log(length);

const todo = { id: 123, content: "HTML", completed: true };

const { id } = todo;
console.log(id);

 

ํ— ์ด๊ฑฐ ์œ ํŠญ๋งŒ๋“ค๊ธฐ์—์„œ ๋ฐฐ์šด๊ฑฐ์ž๋‚˜?

์˜ค์šฐ~~~~~

 

const todos = [
    { id: 1, content: "HTML" },
    { id: 2, content: "CSS" },
    { id: 3, content: "JS" },
];

const [, { id }] = todos;
console.log(id); //2

 

๋ฐฐ์—ด์˜ ์š”์†Œ๊ฐ€ ๊ฐ์ฒด์ธ ๊ฒฝ์šฐ, ๋ฐฐ์—ด ๋””์ŠคํŠธ๋Ÿญ์ฒ˜๋ง ํ• ๋‹น๊ณผ ๊ฐ์ฒด ๋””์ŠคํŠธ๋Ÿญ์ฒ˜๋ง์„ ํ˜ผ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

 

 

์ค‘์ฒฉ ๊ฐ์ฒด ์‚ฌ์šฉ๋ฒ•

const user = {
    name: "ddozza",
    address: {
        zipcode: 12345,
        city: "Seoul"
    }
}

const { address: { city } } = user;

console.log(city); //Seoul

 

 

728x90
๋ฐ˜์‘ํ˜•