arguments의 개념과 활용

Andy·2023년 8월 20일
0

자바스크립트

목록 보기
7/39

arguments란?🤔

arguments란, 함수에 전달되는 인수들을 배열 형태로 나타낸 객체이다.
자바스크립트에서 전달된 인수와 매개변수의 개수는 서로 같지 않아도 된다. 매개변수의 개수보다 인수가 더 적을 경우 넘어오지 않은 값은 undefined로 표시된다.

function arguments(a,b,){
    console.log(a,b);
}
arguments(); //undefined, undefined 출력
arguments('1')// 문자열 1, undefined 출력
arguments(1,2)// 숫자 1, 2 출력
arguments(1,"2",3) //숫자1, 문자열 2 출력

즉, 함수에 넘어오는 인수가 몇 개이든 상관이 없기 때문에 함수가 동작하기 전에 인수의 개수를 확인하여 동작을 해야 한다. 이를 위해 인수를 저장해놓은 공간이 바로 arguments다. argument는 변수 이름이 아닌 키워드이다. 형태만 배열이기 때문에 배열 메서드(map, forEach등)를 사용하면 에러가 뜬다. 전달받은 인수에 접근할 때에는 배열 접근법과 같은 방식으로 접근하면 된다.

function arguments(a,b){
    console.log(arguments[0]); //1출력
    console.log(arguments[1]); //2출력
    console.log(arguments[2]); //undefined 출력
}
arguments(1,2);

arguments 요소는 재할당도 가능하다

function re_arguments(a,b){
    arguments[1]="reset";
    console.log(arguments[0], arguments[1]); //숫자 1, 문자열 reset출력
}
re_arguments(1,2);

화살표 함수에서의 arguments

화살표 함수에는 arguments를 정의할 수 없다.

 var args=(a,b)=>{
    console.log(arguments);
}
args(1,1);

그래서 화살표 함수에서 arguments를 사용하라면 스프레드 문법(...)을 활용해야 한다. 스프레드 문법 사용의 장점은 [object Arguments]가 아닌 [objectArray]즉, 배열로 바로 출력된다는 것이다.

var args=(...arguments)=>{
    console.log(arguments); //[1,2,3] 출력
    console.log(toString.call(arguments)); //[object Array]출력
}
args(1,2,3)

arguments를 배열로 변형

앞서 말했다시피 arguments는 배열이 아닌 유사 배열 객체이기 때문에 배열로 사용하고 싶다면 두개의 방법이 있다.
1. Array.prototype.slice.call(arguments)

function array(a,b,c){
    console.log(toString.call(arguments)) //[object Arguments]
    var arr= Array.prototype.slice.call(arguments); //배열로 변환
    console.log(arr); //[1,2,3]
    console.log(toString.call(arr)); //[object Array]
}
array(1,2,3);

2.)[].slice.call(arguments)

function print(a,b,c){
    var arr = [].slice.call(arguments);
    console.log(arr); //[1,2] 출력
}
print(1,2);

3.) 스프레드 문법 활용

function spread(...args){
    console.log(args); //[1,2,3,4,5] 출력
}
spread(1,2,3,4,5);

arguments활용

그럼 지금까지 배운 arguments를 어디에 활용할 수 있을까?🤔 인수가 몇 개든 arguments에 배열의 형태로 저장해두기 때문에 몇개의 인수가 전달될지 모르는 상황에서 활용하면 된다.

function checkNum(){
    var arr =Array.prototype.slice.call(arguments);
    var check = arr.every(function(value){
        return typeof value === "number"
    });
    console.log(check); //false 출력
}
var number = checkNum(1,2,3,"1");
profile
열정으로 가득 찬 개발자 꿈나무 입니다

0개의 댓글