π΄ Object Destructuring
βͺ ν° μ€λΈμ νΈμμ νΉμ λ³μλ κ·Έ μμ μν μμ μ€λΈμ νΈμ μ κ·Όν μ μλλ‘ νλ κΈ°λ²
const settings = {
notifications: {
follow: true,
alerts: true,
unfollow: false
},
color: {
theme: "dark"
}
};
// const λ³μ μμ±
const {
notifications: { follow },
color
} = settings;
console.log(follow); // true
console.log(color); // {theme: "dark"}
const settings = {
notifications: {
alerts: true,
unfollow: false
},
color: {
theme: "dark"
}
};
// follow κ°μ΄ μλ€λ©΄ falseλ‘ μ€μ νμ¬ μμ±νκ³ , notifications μμ²΄κ° μλ€λ©΄ λΉ object μμ±
const { notifications: { follow = false } = {} } = settings;
console.log(follow); // false
console.log(color); // {theme: "dark"}
π Array Destructuring
const days = ["Mon", "Tue", "Wed"];
const [mon, tue, wed, thu = "Thu"] = days;
console.log(mon, tue, wed, thu); // Mon Tue Wed Thu
π‘ Destructuring Renaming
// [ Rename with const ]
const setting = {
color: {
chosen_color: "dark"
}
};
// chosen_color μμ±μ chosenColor μ΄λ¦μ const λ³μλ‘ μ μ₯
const {
color: { chosen_color: chosenColor = "light" }
} = settings;
console.log(chosenColor); // dark
// [ Rename with let ]
const setting = {
color: {
chosen_color: "dark"
}
};
let chosenColor = "blue";
console.log(chosenColor); // blue
({
color: { chosen_color: chosenColor = "light" }
} = settings);
console.log(chosenColor); // dark
π’ Function Destructuring
function saveSettings({ notifications, color: { theme } }) {
console.log(theme);
}
saveSettings({
notifications: {
follow: true,
alert: true,
mkt: false
},
color: {
theme: "blue"
}
});
π΅ Value Shorthands
βͺ μ€λ³΅λλ λ³μλͺ μ νλλ‘ μ μ΄μ€μΌλ‘μ¨ μ½λλ₯Ό κ°κ²°νκ² νλ λ°©λ²μ΄λ€.
const follow = checkFollow();
const alert = checkAlert();
const settings = {
notifications: {
follow, // === follow: follow
alert // === alert: alert
}
};
π£ Swapping and Skipping
βͺ Swapping
let mon = "Sat";
let sat = "Mon";
[mon, sat] = [sat, mon];
βͺ Skipping λ°°μ΄μ μΌλΆ μμλ₯Ό , λ₯Ό μ¬μ©νμ¬ μ μΈνλ λ°©λ²
const days = ["mon", "tue", "wed", "thu", "fri"];
const [, , , thu, fri] = days;
console.log(thu, fri); // thu fri
'JavaScript' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
[ JS ] For Loop (0) | 2022.07.05 |
---|---|
[ JS ] Rest And Spread (0) | 2022.07.05 |
[ JS ] Array (0) | 2022.07.05 |
[ JS ] Strings (0) | 2022.07.05 |
[ JS ] Functions (0) | 2022.07.05 |