[javascript] 할당된 객체의 속성 변경하기.

자바스크립트에서는 객체의 속성을 쉽게 변경할 수 있습니다.

1. 속성 변경하기

객체의 속성을 변경하려면 . 또는 [] 표기법을 사용합니다.

1.1. 점 표기법

const person = {
  name: "Alice",
  age: 30
};

person.age = 25;
console.log(person.age); // 출력: 25

1.2. 대괄호 표기법

const person = {
  name: "Bob",
  age: 40
};

person["age"] = 35;
console.log(person["age"]); // 출력: 35

2. 참조 변경하기

객체의 속성으로 객체를 할당할 경우 해당 속성이 다른 객체를 참조하고 있는 경우를 변경하면 원본 객체도 함께 변경됩니다.

const person = {
  name: "Charlie",
  address: {
    city: "Seoul",
    postCode: "12345"
  }
};

const newAddress = {
  city: "Busan",
  postCode: "54321"
};

person.address = newAddress;
console.log(person.address.city); // 출력: Busan

하지만, newAddress 객체를 수정하면 person 객체의 속성도 함께 변경됩니다. 이에 유의해야 합니다.

3. 결론

자바스크립트에서는 객체의 속성을 쉽게 변경할 수 있으며, 속성이 다른 객체를 참조하는 경우 원본 객체도 함께 변경될 수 있음을 유의해야 합니다.

참조: MDN Web Docs