[기본문제] 최솟값, 최댓값 구하기

7개의 숫자 중에서 가장 작은 수 출력하기.


forEach

function minNum(...arr) {
  let answer = arr[0];

  arr.forEach((number) => {
    if (answer > number) answer = number;
  });

  return answer;
}

console.log(minNum(5, 3, 7, 11, 2, 15, 17));

for

 function solution(arr) {
  let answer, min = Number.MAX_SAFE_INTEGER;

  for (let i = 0; i < arr.length; i++) {
    if(arr[i] < min) min = arr[i];
  }

  return answer;
}

let arr = [5, 7, 1, 3, 2, 9, 11];

console.log(solution(arr))

Math.min

function solution2(arr) {
  let answer = Math.min(...arr); // spread operator

  return answer;
}

let arr2 = [5, 7, 1, 3, 2, 9, 11];
console.log(solution2(arr2));

Math.min & apply

function solution3(arr) {
  let answer = Math.min.apply(null, arr);

  return answer;
}

let arr3 = [5, 7, 1, 3, 2, 9, 11];

console.log(solution3(arr3));

좋은 웹페이지 즐겨찾기