작성자 : 박소선

검수자 : 배광식

Rest 파라미터

  • 정해지지 않은 수의 파라미터들을 배열로 표현할 수 있게 해준다.

[ES 6 Rest 표현 방식]

function f(a, b, ...theArgs) {
  // ...
}

Rest 기본 예제

function sum(...theArgs) {
  return theArgs.reduce((previous, current) => {
    return previous + current;
  });
}

console.log(sum(1, 2, 3));      // expected output: 6
console.log(sum(1, 2, 3, 4));   // expected output: 10

Rest 파라미터 vs. Arguments 객체 비교

  • Rest 파라미터

    • Rest 파라미터들은 따로 이름이 없다.

    • Rest 파라미터들은 배열 값들이다.

    • sort, map, forEach, pop 메소드를 적용할 수 있다.

  • Arguments 객체

    • Arguments 객체는 배열이 아니다.

    • Arguments 객체에 배열 메소드를 적용하고 싶다면, 배열로 먼저 변환해야한다.

[Arguments 객체]

function f(a, b) {
  var args = Array.prototype.slice.call(arguments, f.length);
  console.log(args);
}

f(1, 2, 3, 4, 5, 6);     // output: (4) [3, 4, 5, 6]
                    // 4는 a,b 파라미터 외에 추가 입력된 파라미터 값 배열의 길이

[Rest 파라미터]

function f(a, b, ...args) {
  console.log(...args);
}

f(1, 2, 3, 4, 5, 6);     // output: 3, 4, 5, 6

Rest 파라미터들을 나눌 수 있다.

function f(...[a, b, c]) {
  return a + b + c;
}

f(1)               // NaN (b and c are undefined)
f(1, 2, 3)         // 6
f(1, 2, 3, 4)      // 6 (4번째 인자는 함수 head에서 정의되지 않았기에 인식하지 못한다.)

results matching ""

    No results matching ""