Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

자바스크립트에서 이미 선언된 변수에 구조 분해 할당하는 방법

자바스크립트의 구조 분해 할당(Destructuring Assignment)은 객체나 배열의 값을 손쉽게 추출해 변수에 담을 수 있는 강력한 문법입니다. 그렇다면 이미 선언된 변수에도 구조 분해 할당을 사용할 수 있을까요? 정답은 '가능하다'입니다. 다만 한 가지 주의할 점이 있습니다.

이미 선언된 변수에 구조 분해 할당하기

변수를 새로 선언하면서 구조 분해할 때는 const { name, age } = obj;처럼 작성하면 됩니다. 하지만 이미 선언된 변수에 값을 할당할 때는 문장이 중괄호({})로 시작하면 코드 블록으로 해석될 수 있으므로, 전체 할당식을 반드시 소괄호(())로 감싸 주어야 합니다.

({ name, age } = personObj);

예제

다음은 자바스크립트에서 이미 선언된 변수에 구조 분해 할당을 수행하는 전체 코드입니다.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
</style>
</head>
<body>
<h1>De-structure to already-declared variables</h1>
<div class="result"></div>
<br />
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to destructure the personObj object</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   let name, age, personObj;
   personObj = {
      name: "Rohan",
      age: 19,
   };
   BtnEle.addEventListener("click", () => {
      ({ name, age } = personObj);
      resEle.innerHTML = " name = " + name + "<br>age = " + age;
   });
</script>
</body>
</html>

출력

위 코드를 실행하면 다음과 같은 화면이 나타납니다.

자바스크립트에서 이미 선언된 변수에 구조 분해 할당하는 방법

'CLICK HERE' 버튼을 클릭하면 personObj 객체의 nameage 값이 각각 미리 선언된 변수에 할당되어 아래와 같이 화면에 표시됩니다.

자바스크립트에서 이미 선언된 변수에 구조 분해 할당하는 방법

정리

이미 선언된 변수에 구조 분해 할당을 적용할 때는 ({ name, age } = personObj);처럼 할당식 전체를 소괄호로 감싸는 것이 핵심입니다. 이를 생략하면 자바스크립트 엔진이 중괄호를 객체 리터럴이 아닌 블록으로 해석하여 문법 오류가 발생할 수 있습니다.