[JS] arguments 객체

파송송계란빡 ㅣ 2023. 2. 16. 00:09

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/arguments

 

arguments 객체 - JavaScript | MDN

arguments 객체는 함수에 전달된 인수에 해당하는 Array 형태의 객체입니다.

developer.mozilla.org

 

arguments

자바스크립트에서는 함수를 호출할 때 인수들과 함께 암묵적으로 arguments 객체가 함수 내부로 전달합니다.

arguments 객체는 함수를 호출할 때 넘긴 인자들이 배열 형태로 저장된 객체를 의미합니다.

실제 배열이 아닌 유사 배열 객체입니다.

function getValue(arr, values) {
    console.log(arr, values);
    console.log(arguments);
}

console.log(getValue([1, 2, 3, 5, 6], "test", { test: 123 }));

 

arguments 객체는 세 부분으로 구성되어 있습니다.

  • [arguments[@@iterator]] : 함수를 호출할 때 넘겨진 인자(배열 형태): 첫 번째 인자는 0, ... n-1번 인덱스
  • [arguments.length] : 호출할 때 넘겨진 인자의 개수
  • [arguments.callee] : 현재 실행 중인 함수의 참조 값
function getValue(arr, values) {
    console.log(arr, values);
    console.log(arguments);
}

console.log(getValue([1, 2, 3, 5, 6], "test", { test: 123 }));

 

arguments 활용

매개변수로 어떤 것이 넘어올 수 알 수 없는 경우 활용 가능합니다.

function getValue(arr, values) {
    console.log("arguments : ", arguments);

    for (let i = 0 ; i < arguments.length ; i++) {
        console.log(`${[i]} ==> ${arguments[i]}`)
    }
}

console.log(getValue([1, 2, 3, 5, 6], "test", { test: 123 }, {test22: 123}, {test44: 123}));

[JS] arguments 객체