본문 바로가기
창고(2021년 이전)

[JS] 매개변수 길이가 유동적일때

by 측면삼각근 2019. 10. 1.
728x90
반응형

1. Rest Parameter

Rest Parameter를 이용해 매개변수를 지정해준다.
MDN : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/rest_parameters
Rest 파라미터는 정해지지 않은 수를 배열로 나타낼 수 있게 한다.

 

Rest 파라미터

Rest 파라미터 구문은 정해지지 않은 수(an indefinite number, 부정수) 인수를 배열로 나타낼 수 있게 합니다.

developer.mozilla.org

예시

function myFun(a, b, ...manyMoreArgs) {
  console.log("a", a); 
  console.log("b", b);
  console.log("manyMoreArgs", manyMoreArgs); 
}

myFun("one", "two", "three", "four", "five", "six");

// Console Output:
// a, one
// b, two
// manyMoreArgs, [three, four, five, six]

 


2. arguments 키워드 이용

예시1

function getMaxNum(){
	console.log(arguments); //{0:3, 1:5 , 2: 8 , 3:10}
}

getMaxNum(;

예시2

function sortRestArgs(...theArgs) {
  var sortedArgs = theArgs.sort();
  return sortedArgs;
}

console.log(sortRestArgs(5, 3, 7, 1)); // 1, 3, 5, 7

function sortArguments() {
  var sortedArgs = arguments.sort(); 
  return sortedArgs; // this will never happen
}


console.log(sortArguments(5, 3, 7, 1)); // TypeError (arguments.sort is not a function)

하지만 코드에 주석이 달려 잇는 것 처럼, '객체'이며 배열이 아니라 배열의 메소드를 사용 할 수 없다.

반응형

'창고(2021년 이전)' 카테고리의 다른 글

[JS] this  (0) 2019.10.07
[JS] DOM(Document Object Model)  (0) 2019.10.03
[JS] 클로저(예시 위주)  (0) 2019.10.01
Test 기반 개발방법  (0) 2019.10.01
[Git] Command Line  (0) 2019.09.30