Stack/JavaScript

[JS] 구조분해 할당

7ingout 2022. 5. 23. 09:45

구조 분해 할당

(React에서 많이 쓰임)

배열과 객체의 값을 분해해서 변수에 할당해줌

배열의 값을 복사한 후 변수에 할당해주므로 배열이 수정 또는 파괴되지 않습니다.

 

let fruits = ["사과", "수박", "오렌지", "딸기"]

let fruit1 = fruits[0];

let fruit2 = fruits[1];

let fruit3 = fruits[2];

let fruit4 = fruits[3];

 

1) 기본구문 let [변수명, 변수명, ...] = 배열변수

ex> let [fruit1, fuit2, fruit3, fruit4] = fruits;

 

2) 쉼표를 사용하여 요소 무시하기

let frutis = ["사과", "수박", "오렌지", "딸기"]

let [fruit1, , fruit2] = fruits;

 

3) 변수의 값을 교환

변수에 할당된 값을 교환할 때도 구조분해 할당을 사용할 수 있음

구문> [변수, 변수2] = [변수2, 변수1];

ex>

let name = "green";

let admin = "admin";

admin엔 "green", name엔 "admin"

[name, admin] = [admin, name];

 // 원래 하던 교환 방법

let temp;

temp = name;

name = admin;

admin = temp;

 

4) 나머지 매개변수를 활용한 나머지 요소 배열로 가져오기

구문> let [변수명1, 변수명2, ...변수명3] = 배열변수

ex> 

let frutis = ["사과", "수박", "오렌지", "딸기"]

let [fruit1, fruit2, ...fruit3] = fruits;

 

* 객체 구조분해 할당

구조분해 할당으로 객체도 분해할 수 있음

구문 > let {변수명1, 변수명2} = {키1: ..., 키2: ...}

let options = {

        width: 100,

        height: 200,

        title: "Menu",

}

let {title, width, height} = options;

 

1) 객체의 키와 다른 변수명으로 할당

객체 키명: 변수명

let options = {

        width: 100,

        height: 200,

        title: "Menu",

}

let {title, width: w, height} = options;

let {title} = options;

 

2) 나머지 패턴 '...'

let options = {

        width: 100,

        height: 200,

        title: "Menu",

}

let {title, ...rest} = options

 

 


 

decomposition.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        let fruits = ["🍓", "🍒", "🥥", "🍅", "🍉"];

        // let fruit1 = fruits[0];
        // let fruit2 = fruits[1];
        // let fruit3 = fruits[2];
        // let fruit4 = fruits[3];
        // console.log(fruit1);
        // console.log(fruit2);
        // console.log(fruit3);

        // 구조분해 할당
        let [fruit1, fruit2, , , fruit3] = fruits;
        console.log(fruit1, fruit2, fruit3);
        
        // 나머지 매개변수로 배열로 받기
        let [fru, ...frus] = fruits;
        console.log(`fru변수에 담긴 값은: ${fru}입니다.`);
        console.log(`frus에 담긴 값은: ${frus}배열입니다.`);
        console.log(frus);

        // 변수값 변경하기
        let green = "green";
        let blue = "blue";
        console.log(`green변수에 담긴 값은 ${green}이다.`);
        console.log(`blue변수에 담긴 값은 ${blue}이다.`);
        [green, blue] = [blue, green];  // 변수값 변경
        console.log(`green변수에 담긴 값은 ${green}이다.`);
        console.log(`blue변수에 담긴 값은 ${blue}이다.`);

        let [a, b, c] = ["green", "blue", "pink"];

        // 기본값 
        let [name = "bob", age = 30] = ["guest", 50]; // let [여기는 기본값]
        console.log(name);
        console.log(age);


        // 객체 구조분해 할당
        let options = {
            title: "Menu",
            width: 100,
            height: 200,
        }
        let {width, height}= options;
        console.log(width);

        // 키명과 다른 변수명으로 할당
        let {title: m} = options;
        console.log(m);
        
        // 객체 구조분해 할당 나머지 할당하기
        let {title, ...rest} = options;
        console.log(`title변수에는 ${title}이 할당됨`);
        console.log(`rest변수에는 ${rest} title을 제외한 나머지 객체가 할당됨`);
        console.log(rest);
        
        // 객체 구조분해 할당 기본값 설정하기
        let person1 = {
            name2: "bob",
            age2: 30,
            subname: "abc",
            isJob: true,
            hobby: "음악감상",
        }
        let {name2: n, age2: ab, subname, hobby} = person1;
        console.log(hobby); // 없으면 undefined 

        let opt = {
            title2: "Menu"
        }
        let { 
            width2 = prompt("width?"), 
            height2 = prompt("height?"), 
            title2 } = opt;
        
        console.log(width2, height2, title2);
    </script>
</body>
</html>

 

decomposition_ex.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        let user = {
            name: "John",
            years: 30
        };

        // name 프로퍼티의 값을 변수 name에 할당하세요.
        // years 프로퍼티의 값을 변수 age에 할당하세요.
        // isAdmin 프로퍼티의 값을 변수 isAdmin에 할당하세요.
        // isAdmin이라는 프로퍼티가 없으면 false를 할당하세요.
        
        let {name, years: age, isAdmin = false } = user;
        console.log(name, age, isAdmin);
    </script>
</body>
</html>

 

구조분해할당복습.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        let arr = [1, 2, 3,, 4, 5];
        let a = arr[0];
        let b = arr[1];
        let [c, d] = arr;
        let newobj = {
            name: 'bella',
            age: 30,
        }
        let name1 = newobj['name'];
        let age1 = newobj['age'];
        let { name, age:ag } = newobj;
        console.log(name);
        console.log(ag);
    </script>
</body>
</html>