Spread 연산자는 연산자의 대상 배열 또는 이터러블(iterable)을 개별 요소로 분리한다. 이터러블(iterable)은 Array, String, Map, Set, DOM구조다. iterator를 생성해서 next()로 순회할 수 있는 자료구조가 이터러블이다.
const arr = [1, 2, 3, 4, 5];
console.log(arr); // [ 1, 2, 3, 4, 5 ]
console.log(...arr); // 1, 2, 3, 4, 5
console.log([...arr]) // [ 1, 2, 3, 4, 5 ]
Rest 파라미터는 Spread 연산자(...)를 사용하여 함수의 파라미터(매개변수)를 작성한 형태를 말한다. 즉, Rest 파라미터를 사용하면 함수의 파라미터로 오는 값들(함수를 호출할 때 넣어주는 인수)을 배열로 전달받을 수 있다. Rest파라미터는 항상 제일 마지막 파라미터로 있어야 한다. 당연히 배열이므로 배열 메서드를 사용할 수 있다.
function foo(...rest) {
console.log(Array.isArray(rest)); // true
console.log(rest); // [ 1, 2, 3, 4, 5 ]
}
foo(1, 2, 3, 4, 5);
유사 배열객체이므로 배열 메서드를 사용할 수 없다. 유사 배열 객체(array-like object)는 간단하게 순회가능한(iterable) 특징이 있고 length 값을 알 수 있는 특징이 있는 것이다. 즉, 배열처럼 사용할 수 있는 객체를 말한다.
function func1(a, b, c) {
console.log(arguments[0]);
// expected output: 1
console.log(arguments[1]);
// expected output: 2
console.log(arguments[2]);
// expected output: 3
}
func1(1, 2, 3);
Array.from() 메서드 또는 spread 연산자를 사용하면 진짜 배열로 바꿀 수 있다.
let args = Array.from(arguments);
let args = [...arguments];
[참고]
1. https://jeong-pro.tistory.com/117 [기본기를 쌓는 정아마추어 코딩블로그]
2. https://developer.mozilla.org/ko/