Destructuring을 사용하여 자바스크립트에서 특정 값을 변경하는 방법
title: “Destructuring을 사용하여 자바스크립트에서 특정 값을 변경하는 방법” description: “Destructuring을 활용하여 자바스크립트에서 특정 값 변경하기” date: “2021-08-31” categories:
- JavaScript tags:
- JavaScript
-
Destructuring
Destructuring은 JavaScript에서 변수로부터 값을 추출하여 사용하는 편리한 기능입니다. 이를 사용하면 객체나 배열에서 필요한 값만 추출하여 변수로 할당하거나, 객체의 속성을 직접 해체하여 간편하게 접근할 수 있습니다.
Destructuring을 활용하여 특정 값을 변경하는 방법에 대해 알아보겠습니다.
객체에서 특정 속성 값 변경하기
const person = {
name: "John",
age: 30,
city: "New York"
};
const {
name,
age,
city
} = person;
console.log(name, age, city); // John 30 New York
const modifiedPerson = {
...person,
age: 31
};
console.log(modifiedPerson); // { name: "John", age: 31, city: "New York" }
위의 예시에서는 person
객체에서 name
, age
, city
속성을 추출하여 새로운 변수로 할당한 후, age
속성 값을 변경하고 새로운 객체 modifiedPerson
을 생성했습니다. 이렇게 하면 person
객체를 직접 수정하지 않고도 필요한 값을 변경할 수 있습니다.
배열에서 특정 요소 값 변경하기
const colors = ["red", "green", "blue"];
const [firstColor, secondColor, thirdColor] = colors;
console.log(firstColor, secondColor, thirdColor); // red green blue
const modifiedColors = [...colors];
modifiedColors[1] = "yellow";
console.log(modifiedColors); // ["red", "yellow", "blue"]
배열에서는 인덱스를 사용하여 특정 요소의 값을 직접 변경할 수 있습니다. 위의 예시에서는 colors
배열의 첫 번째, 두 번째, 세 번째 요소를 추출하여 새로운 변수로 할당한 후, 두 번째 요소의 값을 “yellow”로 변경한 배열 modifiedColors
를 생성했습니다.
Destructuring은 JavaScript에서 특정 값을 간편하게 추출하고 변경할 수 있는 편리한 기능입니다. 이를 활용하여 코드를 더 읽기 쉽고 간결하게 작성할 수 있습니다.