[JS] ꡬ쑰λΆν΄(Destructuring) (feat. μ½κ² λ³μ λ§λ€κΈ°)
μλ νμΈμ 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