[JavaScript] 요소의 객체화 (rest parameter)

function getAllParamsByArgumentsObj() {
      return arguments;
}
const argumentsObj = getAllParamsByArgumentsObj('first', 'second', 'third');

console.log(Object.keys(argumentsObj)); //['0', '1', '2']
console.log(Object.values(argumentsObj)); //['first', 'second', 'third']
console.log(Array.isArray(argumentsObj)); //false

spread syntax, 즉 스프레드 함수의 rest parameter 기능을 이용해 쉽게 요소를 배열로 만들 수 있다.

function getAllParamsByRestParameter(...args) {
      return args;
}
const restParams = getAllParamsByRestParameter('first', 'second', 'third');
    
console.log(restParams); //['first', 'second', 'third']
console.log(Array.isArray(restParams)); //true

 

아래는 ES6이전 arguments를 통해 spread syntax와 비슷하게 함수의 전달인자들을 다룬 방법이라고 한다.

함수를 이용해 arguments를 리턴하면 객체를 반환한다.

 

예시코드는 코드스테이츠 과제 koans 를 참고했다.