본문 바로가기
프로그래밍/Java Script

Java Script - Rest parameter

by 3.14pie 2022. 12. 11.

Rest parameter - 함수에 전달된 인자의 목록을 배열로 받는 매개변수이다. 매개변수 이름 앞에 ...을 붙여 사용한다.

        function calc(x, y, z){
            let sum = x + y + z;
            console.log(sum);

            return sum;
        }

        calc(8, 3, 4);

변수가 많이 필요한 경우, 모든 변수를 지정해 작업하기 복잡하다. 여기서 rest parameter를 사용하면 모든 변수를 지정하지 않아도 된다.

        function calc2(...input){
            let total = 0;

            for (let x of input) {
                total += x;
            }

            console.log(total);
            return total;
        }

        calc2(5,8,12,6);

앞에 ...을 붙여 input을 rest parameter로 선언하고 for of문을 통해 배열로써 연산이 가능하다. 변수를 몇 개 선언해도 상관없다.

        function calc3(...input){
            let total = 0;

            input.forEach(function(x, index){
                console.log(index);
                total += x;
            });

            console.log(total);
            return total;
        }

        calc3(5,8,12,6);

rest parameter로 받으면 배열의 형태가 되기 때문에 forEach문을 사용할 수도 있다. 현재 index도 확인할 수 있다.

'프로그래밍 > Java Script' 카테고리의 다른 글

Java Script - Template literals  (0) 2022.12.11
Java Script - Arrow function  (0) 2022.12.11
Java Script - Default function parameter  (0) 2022.12.11
Java Script - scope  (0) 2022.12.11
Java Script - this  (0) 2022.12.11