TIL - 13 | Rest parameter, Spread syntax

dk.han·2021년 8월 5일
0
post-thumbnail

Rest parameter

  • 변수 앞에 spread operator (... 세개의 점)를 붙여서 사용하는 매개변수를 의미한다.
  • Rest 파라미터를 사용하면 함수에 전달되는 argument 목록을 배열로 받는다.
function foo(...rest) {
  console.log(Array.isArray(rest)); // true
  console.log(rest); // [ 1, 2, 3, 4, 5 ]
}

foo(1, 2, 3, 4, 5);
  • argument들은 순차적으로 param 와 Rest 파라미터에 할당된다
  • function bar(...rest, param1, param2) Rest 파라미터는 첫번째 변수가 될 수 없다.
  • 항상 마지막에 위치해야 한다.
function bar(param1, param2, ...rest) {
  console.log(param1); // 1
  console.log(param2); // 2
  console.log(rest);   // [ 3, 4, 5 ]
}

bar(1, 2, 3, 4, 5);

Rest 파라미터는 파라미터 개수가 가변적인 함수일 때 유용하다!!

arguments 객체 VS Rest 파라미터

  • arguments 객체는 유사 배열 객체이고, Rest 파라미터는 배열이다.
  • 유사 배열 객체는 배열처럼 보이지만, 객체의 성격을 가지므로 배열 Method를 사용 할 수 없다.
  • 유사 배열 객체는 Object객체의 Method를 사용 할 수 있다.
  • 유사 배열 객체는 key 값으로 index를 리턴한다.
function getAllParamsByRestParameter(...args) {
      return args;
    }
function getAllParamsByArgumentsObj() {
      return arguments;
    }

const restParams = getAllParamsByRestParameter('first', 'second', 'third');
const argumentsObj = getAllParamsByArgumentsObj('first', 'second', 'third');

console.log(typeof restParams) // object
console.log(typeof argumentsObj) // object
console.log(Array.isArray(restParams)) // true
console.log(Array.isArray(argumentsObj)) // false
console.log(Object.keys(argumentsObj)) // ["0", "1", "2"])
console.log(Object.values(argumentsObj)) // ['first', 'second', 'third']

Spread syntax

  • Spread 문법은 대상을 개별 요소로 분리한다.
  • 배열을 풀어서 인자로 전달하거나, 각각의 요소로 넣을 때 주로 사용한다.
function foo(x, y, z) {
  console.log(x); // 1
  console.log(y); // 2
  console.log(z); // 3
}
const arr = [1, 2, 3];
foo(...arr); // Array를 매개변수로 전달.
  • Spread 문법을 사용해 매개변수를 정의 한 것이 Rest 파라미터이다.
function foo(param, ...rest) {
  console.log(param); // 1
  console.log(rest);  // [ 2, 3 ]
}
foo(1, 2, 3);
  • Spread 문법을 사용한 인수는 해당 매개변수로 각각의 요소가 분리되여 전달된다.(Rest 파라미터 X)
  • Rest 파라미터는 반드시 마지막 파라미터이어야 하지만 Spread 문법을 사용한 인수는 자유롭게 사용할 수 있다.
function bar(x, y, z) {
  console.log(x); // 1
  console.log(y); // 2
  console.log(z); // 3
}
bar(...[1, 2, 3]);

배열에서 spread syntax 사용법

  • 배열을 복사하기 위해서는 slice Method를 사용한다.
var arr  = [1, 2, 3];
var copy = arr.slice();

console.log(copy); // [ 1, 2, 3 ]

// copy를 변경한다.
copy.push(4);

console.log(copy); // [ 1, 2, 3, 4 ]
// arr은 변경되지 않는다.
console.log(arr);  // [ 1, 2, 3 ]
  • Spread 문법도 slice와 마찬가지로 기존 배열을 변경하지 않으므로 immutable 이다.
const arr = [1, 2, 3];
const copy = [...arr];

console.log(copy); // [ 1, 2, 3 ]
copy.push(4);

console.log(copy); // [ 1, 2, 3, 4 ]
// arr은 변경되지 않는다.
console.log(arr);  // [ 1, 2, 3 ]
  • arr.concat() method처럼 배열 합치기가 가능하다.
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
arr1 = [...arr1, ...arr2]; 

console.log(arr1) // [0, 1, 2, 3, 4, 5]

객체에서 spread syntax 사용법

  • obj1 과 clonedObj의 key와 value는 같지만 reference는 다르다.
  • 객체끼리 합칠 때, 같은 key값이 존재하면 뒤에오는 객체의 value로 덮어쓴다.
let obj1 = { foo: 'bar', x: 42 };
let obj2 = { foo: 'baz', y: 13 };

let clonedObj = { ...obj1 };
let mergedObj = { ...obj1, ...obj2 };

console.log(clonedObj) // {foo: "bar", x: 42}
console.log(mergedObj) // {foo: "baz", x: 42, y: 13}
console.log(clonedObj === obj1) // false

이 다음으로는 shallow copy와 deep copy에 대해 알아보도록 하겠다.

0개의 댓글