개발 공부/Javascript
함수에 매개변수로 들어가 있는 ...은 rest parameter
차정
2023. 3. 24. 12:45
[출처]
https://medium.com/free-code-camp/how-do-javascript-rest-parameters-actually-work-227726e16cc8
How JavaScript rest parameters actually work
My last article covered spread syntax and Object.assign in detail, but glossed over rest parameters in the interest of time. I do, however…
medium.com
내부동작을 살펴보면 이렇다.
someFunction = (...args) => args;
위 someFunction 함수는 아래와 같다. (옛날 문법으로 풀어서 보기)
someFunction = function someFunction() {
var _len = arguments.length;
// create an array same length
// as the arguments object
var args = Array(_len);
var i = 0;
// iterate through arguments
for (i; i < _len; i++) {
// assign them to
// the new array
args[i] = arguments[i];
}
// and return it
return args;
};
즉 someFunction 은 매개변수로 넣은 인자들을 담은 배열을 반환하는 함수다.
someFunction('a','b','c')
// ['a', 'b', 'c']
- arguments는 for loop 돌수있으나 배열은 아니다
- 그러나 rest parameter는 배열이다.
- es6문법에 rest parameter, map, filter등이 도입되었다.
이것으로 함수형 프로그래밍을 할 수 있다.