[TIL] JS 기본편 - 함수의 기본 형태 예제 톺아보기

👉🏼 KIM·2023년 5월 28일
0

TIL

목록 보기
7/9
post-thumbnail

함수는 코드의 집합니다. 함수의 자료형은 function이며,
익명 함수, 선언적 함수가 있다. 함수에 관련된 예제를 몇가지 풀면서 함수와 더 친해지게 되었다.

  1. A부터 B까지 범위를 지정했을 때 범위 안의 숫자를 모두 곱하는 함수를 만들어보자.
function multiply(a,b) {
    let output = 1;
    for(let i = a; i <=b; i++) {
        output *= i
    }
    return output
}

console.log(multiplyAll(1, 2))//2
console.log(multiplyAll(1, 3))//6
  1. 다음 과정에 따라 최대값을 찾는 max() 함수를 만들어보자.
  • 매개변수로 max([1, 2, 3, 4])와 같은 배열을 받는 max()를 만들어보자. (최대값을 구하는 함수)
  const max = function (array) {
    let output = array[0];
    for (arr in array) {
      if (output < array[arr]) {
        output = array[arr];
      }
    }
    return output;
  };

  console.log(max([1, 2, 3, 4]));//4
  • 매개변수로 max(1, 2, 3, 4)와 같은 배열을 받는 max()를 만들어보자. (나머지 매개변수를 사용한 min() 참고)
  const max = function (...array) {
    let output = array[0];
    for(const arr of array) {
    	if(output < arr) {
        	output = arr
        }
    }
    return output;
  };

  console.log(max(1, 2, 3, 4));
  • max([1, 2, 3, 4]) 형태와 max(1,( 2, 3, 4) 형태를 모두 입력할 수 있는 max() 함수를 만들어보자. (매개변수의 자료형에 따라 다르게 작동하는 min() 참고)
const max = function(first, ...rests) {
  let output
  let items

  //매개변수의 자료형에 따라 조건 분기하기
  if(Array.isArray(first)) {
    output = first[0]
    items = first
  } else if(typeof(first) === 'number') {
    output = first
    items = rests
  }

  //최대값 구하는 공식
  for(const item of items) {
  	if(output < item) {
    	output = item
    }
  }
  
  return output
}

console.log(`max(배열): ${max([1,2,3,4])}`) //4
console.log(`max(배열): ${max(1,2,3,4)}`) //4

profile
프론트는 순항중 ¿¿

0개의 댓글