[Javascript]Rest Parameter

phoenix·2021년 9월 26일
0

Rest Parameter는 MDN에도 나와있는데
ES6문법으로 작성하고 있다면 arguments대신 rest parameter로 작성하라고 써있다

Note: If you're writing ES6 compatible code, then rest parameters should be preferred.

source:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments

The rest parameter syntax allows a function to accept an indefinite number of arguments as an array,

Rest Parameter는 파라미터 앞에 마침표 세개 ... 을 붙여주게되는데 이렇게 하면 여러 개로 전달된 arguments들을 배열로 다룰 수가 있게 된다

먼저 arguments는 "array-like" object로써 배열같은 객체다 따라서 배열의 메소드들을 사용할수 없었는데

Rest parameter는 배열이여서 배열의 메소드를 자유롭게 사용할 수 있다

function printRankingList(first, second, ...others) {
  console.log('대회 결과');
  console.log(`우승자: ${first}`);
  console.log(`준우승자: ${second}`);
  for (const arg of others) {
    console.log(`참가자: ${arg}`);
  }
}

printRankingList('철수', 'Jerry', 'Kerry', 'Tom', '영수');

profile
phoenix

0개의 댓글