본문 바로가기
JavaScript/기초

자바스크립트[기초] 함수의 가변인자 arguments 객체

by 뿌비 2022. 4. 19.
728x90
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/arguments [참고]

  • 자바스크립트는 데이터가 다 객체이기 때문에 매개변수 x, y는 값을 담는 역할이 아닌 그냥 값을 참조하는 이름일 뿐이다.
  • 그래서  매개변수가 x, y  2개뿐일 때에도  document.write(add(14, 3, 25, 1, 2, "hello", "hi")); 를 통해 값을 아무리 많이 넘겨도 오류가 나지 않는다 
  • 넘겨진 객체들은 function 안에서 가변적으로 사용 할 수 있는 객체 arguments에 다 저장된다 
  • 그 객체들에 하나씩 접근하기 위해서는 arguments [index]를 통해 접근하면 된다.
    <script>
        function add(x, y) {
            console.log(typeof arguments[1]); //number
            console.log(typeof arguments[5]); //string
            console.log(arguments[1]); // 3
            console.log(arguments[3]); // 1
            console.log(arguments[5]); // hello
            console.log(x + y); // 17
            return x + y;
        }
        document.write(add(14, 3, 25, 1, 2, "hello", "hi"));
    </script>

 

 

728x90