ES6 파라미터
- 파라미터 기본값
es5에서는 파라미터 기본값을 설정할 수 없었지만, es6에선 기본값을 설정할 수 있어 함수 내 파라미터 검사를 수행하지 않아도 된다.
- Rest 파라미터
Rest 파라미는 Spread 연산자를 사용하여 파라미터를 정의한 것이다. 그래서 인수 리스트를 함수 내부에서 배열로 전달받을 수 있다.
function foo(...rest) {
console.log(Array.isArray(rest));
console.log(rest);
}
foo(1,2,3,4,5);
위 결과로 볼 수 있듯이 인수는 순차적으로 파라미터와 Rest 파라미터에 할당된다.
또한 주의할 점은 rest 파라미터는 항상 인수의 맨 마지막에 와야 한다는 것이다. 그렇게 하지 않을 시 문법에러가 발생한다.
- argumetns와 rest 파라미터
es5의 가변 인자 함수는 arguments 객체를 통해서 인수를 확인했다.
var foo = fucntion() {
console.log(arguments);
};
foo(1,2);
arguments는 파라미터로 인수를 전달받는 것이 불가능했다. 또한 유사 배열 객체이기 때문에 배열 메서드를 사용하기 위해선 Function.prototype.call을 사용해야 하는 불편함이 있었다.
하지만 es6에서는 rest 파라미터를 통해 가변 인자를 함수 내부에 배열로 전달이 가능하다. 위처럼 arguments 객체를 배열로 변경하는 등의 수고스러움을 덜 수 있다.
function sum(...args) {
console.log(arguments)
console.log(Array.isArray(args));
return args.reduce((pre,cur) => pre + cur);
}
console.log(sum(1,2,3));
주의할 점은 화살표 함수에는 arguments 프로퍼티가 없기 떄문에 화살표 함수로 가변 인자 함수롤 구현해야 한다면 반드시 rest 파라미터를 사용해야 한다.
- Spread 연산자
spread 연산자는 대상 배열이나 이터러블을 개별 요소로 분리한다.
- 함수 인자로 사용하는 경우
원래라면 Function.prototype.apply를 통해 개별적인 파라미터로 전달했다. 하지만 spread 연산자를 이용하면 쉽게 매개변수로 전달이 가능하다.
function foo(x,y,z) {
console.log(x);
console.log(y);
console.log(z);
}
const arr = [1,2,3];
foo(...arr);
…rest와 spread연산자의 차이는 …rest는 분리된 요소를 함수 내부에 배열로 전달한다는 것이고 spread 연산자는 매개변수에 할당한다는 것이다.
또한 spread연산자는 자유롭게 사용할 수 있다.
- 배열에서 사용할 경우
es5에서는 기존 배열에 대한 많은 메서드를 사용하여 해결해야 했지만 spread 연산자로 좀 더 편하고 가독성이 좋게 만들 수 있다.
concat
var arr = [1,2,3]; console.log(arr.concat([4,5,6])); const arr = [1,2,3]; console.log([...arr,4,5,6]);
push
var arr1 = [1,2,3]; var arr2 = [4,5,6]; Array.prototype.push.apply(arr1, arr2); console.log(arr1); const arr1 = [1,2,3]; const arr2 = [4,5,6]; arr1.push(...arr2); console.log(arr1);
splice
var arr1 = [1,2,3,6]; var arr2 = [4,5]; Array.prototype.splice.apply(arr1, [3,0].concat(arr2)); console.log(arr1); const arr1 = [1,2,3,6]; const arr2 = [4,5]; arr1.splice(3,0,...arr2); console.log(arr1);
slice
var arr = [1,2,3]; var copy = arr.slice(); console.log(copy); copy.push(4); console.log(copy); console.log(arr);
원본 배열에 변화는 없다.
const arr = [1,2,3];
const copy = [...arr];
console.log(copy);
객체에서 사용하는 경우
cost merged = {…{x:1, y:2 }, …{y: 10, z: 3}};
console.log(merged);const changed = {…{x:1, y:2 }, y:100};
console.log(changed);const added = {…{x:1, y:2},z:0};
console.log(added);
Object.assign 메서드를 사용해도 같은 작업이 가능하다.
const merged = Object.assign({}, {x:1, y:2}, {y: 10, z: 3});
console.log(merged);
const changed = Object.assign({}, {x:1, y:2}, {y: 100});
console.log(changed);
const added = Object.assign({}, {x:1,y:2}, {z:0});
console.log(added);
spread연산자를 사용하여 유사 배열 객체를 손쉽게 배열로 변경할 수 있다.
const htmlCollection = document.getElementByTagName('li');
const newArray = [...htmlCollection];
위 예제는 html 파일을 만들어서!
Array.from 메서드로도 가능하다.