웹(WEB)/자바스크립트(JS)

자바스크립트 Spread, Rest

마달랭 2024. 8. 5. 15:20
반응형

개요

1. Spread

객체/배열을 통째로 끌고와서 펼치는 형태

초기화된 객체 혹은 배열을 ...객체명 을 통해 해당 요소들을 전부 가져올 수 있다.

 

2. Rest

나머지 객체, 배열을 Rest에 담아서 추출하는 방법

 

예제

1. 객체 Spread

코드

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        // 객체 Spread
        const square = {
            width : 200,
            height : 200
        }

        const colorSquare = {
            ...square,
            color: 'red'
        }
        square.width = 240; // colorSquare에는 변경 x

        console.log(square);
        console.log(colorSquare);
    </script>
</body>
</html>

 

출력

 

2. 배열 Spread

코드

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        // 배열 Spread
        const catTypeAnimals = ['고양이', '호랑이'];
        const dogTypeAnimals = ['개', '늑대'];

        const allTypeAnimals = [...catTypeAnimals, ...dogTypeAnimals, '비버'];

        console.log(allTypeAnimals);
    </script>
</body>
</html>

 

출력

3. 객체 Rest

코드

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        // Rest
        const chicken = {
            type : '양념',
            drumsticks : 2,
            wing : 2,
        }

        const {type, ...another} = chicken;
        console.log(type);
        console.log(another);
    </script>
</body>
</html>

 

출력

4. 배열 Rest

코드

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        // Rest
        const numberArray = [0, 1, 2, 3, 4, 5, 6];
        const [one, two, ...another] = numberArray;
        
        console.log(one);
        console.log(two);
        console.log(another);
    </script>
</body>
</html>

 

출력

 

728x90
반응형