๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ“Œ Language/Javascript

[JS] ๊ตฌ์กฐ๋ถ„ํ•ด(Destructuring) (feat. ์‰ฝ๊ฒŒ ๋ณ€์ˆ˜ ๋งŒ๋“ค๊ธฐ)

by Fomagran ๐Ÿ’ป 2022. 2. 5.
728x90
๋ฐ˜์‘ํ˜•

 

์•ˆ๋…•ํ•˜์„ธ์š” Foma ๐Ÿ’ป ์ž…๋‹ˆ๋‹ค!

 

์˜ค๋Š˜์€ JavaScript์—์„œ ์•„์ฃผ ์œ ์šฉํ•˜๊ฒŒ ๋ณ€์ˆ˜๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ๊ตฌ์กฐ๋ถ„ํ•ด์— ๋Œ€ํ•ด ์•Œ์•„๋ณด๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.

 

๋ฐ”๋กœ ์‹œ์ž‘ํ• ๊ฒŒ์š”~


๋ฐฐ์—ด ๋ถ„ํ•ดํ•ด์„œ ๋ณ€์ˆ˜ ๋งŒ๋“ค๊ธฐ

 

๋Œ€๊ด„ํ˜ธ๋ฅผ ์ด์šฉํ•ด์„œ ๋ณ€์ˆ˜์— ๊ฐ’์„ ํ• ๋‹นํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

let arr = ["foma","gran"]
let [foma,gran] = arr
console.log(foma) //"foma"
console.log(gran) //"gran"

๋ฌธ์ž์—ด ๋ถ„ํ•ดํ•ด์„œ ๋ณ€์ˆ˜ ๋งŒ๋“ค๊ธฐ

 

๋ฌธ์ž์—ด์„ ์›ํ•˜๋Š” ๋‹จ์œ„๋กœ ๋ถ„ํ•ดํ•˜์—ฌ ๋ณ€์ˆ˜๋กœ ๋งŒ๋“ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

let fomagran = "foma,gran"
let [foma,gran] = fomagran.split(',')
console.log(foma) //"foma"
console.log(gran) //"gran"

์›ํ•˜๋Š” ์š”์†Œ๋งŒ ๋งŒ๋“ค๊ธฐ

 

์‰ผํ‘œ์™€ ๊ณต๋ฐฑ์„ ์ด์šฉํ•˜์—ฌ ๊ฑด๋„ˆ ๋›ธ ์ˆ˜ ์žˆ๊ณ  ์›ํ•˜๋Š” ๊ธธ์ด๊นŒ์ง€๋งŒ ๋ณ€์ˆ˜๋กœ ๋งŒ๋“ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

let names = ["foma"."gran","fomagran","young"]
let [foma, ,fomagran] = names
console.log(foma) //foma
console.log(fomagran) //fomagran

๋‚˜๋จธ์ง€ ํ•œ ๋ฒˆ์— ๋ฌถ์–ด์„œ ์ง€์ •ํ•˜๊ธฐ

 

...์„ ์ด์šฉํ•ด์„œ ๋‚จ์€ ๋ณ€์ˆ˜๋“ค์„ ๋ชจ๋‘ ๋‹ด์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

let names = ["foma"."gran","fomagran","young"]
let [foma,gran,...rest] = names
console.log(foma) //foma
console.log(rest) //["fomagran","young"]

๊ฐ์ฒด ๋ถ„ํ•ดํ•˜๊ธฐ

 

๊ฐ์ฒด๋Š” ๋ฐฐ์—ด์ด๋‚˜ ๋ฌธ์ž์—ด๊ณผ ๋‹ค๋ฅด๊ฒŒ ์ค‘๊ด„ํ˜ธ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋ณ€์ˆ˜๋ฅผ ์ง€์ •ํ•ฉ๋‹ˆ๋‹ค.

 

let user = {
    name:"fomagran",
    age:27,
    color:"Black"
}
let {name,age,color} = user
console.log(name) //"fomagran"

 

ํ”„๋กœํผํ‹ฐ๋ช…:์›ํ•˜๋Š” ์ด๋ฆ„์œผ๋กœ ์ง€์ •ํ•  ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค.

 

let {name:n,age:a,color:c} = user
print(n) //"fomagran"

 

ํ”„๋กœํผํ‹ฐ๊ฐ€ ์—†์„ ๋•Œ๋‚˜ ๊ฐ’์ด ์—†์„ ๋•Œ๋ฅผ ๋Œ€๋น„ํ•˜์—ฌ ๊ธฐ๋ณธ๊ฐ’์„ ์„ค์ •ํ•  ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค.

 

let {name:n = "Fomagran",age:a = 27,color:c = "Blue",food:f = "Rice"} = user
print(f) //"Rice"

์ค‘์ฒฉ๊ตฌ์กฐ ๋ถ„ํ•ดํ•˜๊ธฐ

 

์ค‘์ฒฉ์œผ๋กœ ๋˜์–ด์žˆ๋Š” ๊ตฌ์กฐ๊ฐ€ ์žˆ๋‹ค๋ฉด ์ค‘๊ด„ํ˜ธ ์•ˆ์— ์ค‘๊ด„ํ˜ธ๋‚˜ ๋Œ€๊ด„ํ˜ธ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๊ฐ’์„ ์ง€์ •ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

let options = {
    size: {
        width:100,
        height:90
    },
    items:["Cake","Donut"],
    isOkay:false
}

let {size:{width,height},items:[item1,item2]} = options
console.log(width) //100
console.log(item1)//"Cake"

ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ๋ถ„ํ•ดํ•˜๊ธฐ

 

ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ๊ฐ์ฒด๋ฅผ ๋ฐ›์„ ๋•Œ ๋ถ„ํ•ดํ•˜์—ฌ ๊ฐ’์„ ์–ป์–ด๋‚ผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

function showOption({title = "title",items:[item1,item2]}) {
    print(`${title} ${item1} ${item2}`)
}
showOption(options)
// title Cake Donut

Reference

 

๋ชจ๋“  JS ์ง€์‹์€ ๋ชจ๋˜ JavaScript ํŠœํ† ๋ฆฌ์–ผ์„ ํ†ตํ•ด ํ•™์Šตํ•˜์˜€์Šต๋‹ˆ๋‹ค.

 

 

๋ชจ๋˜ JavaScript ํŠœํ† ๋ฆฌ์–ผ

 

ko.javascript.info

 

728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€