본문 바로가기

verdantjuly/코딩테스트

javascript Math.max.apply(Math, array)

728x90

알게 된 것

 

배열 요소의 합 구하는 법

Math.max.apply(Math, array)

 

Math.min 또는 Math.max 함수는 소괄호 안의 것을

배열이 아니라 고유한 변수를 기대한다.

따라서 Math.max(배열) 의 값은 NaN이 나온다. 

 

이를 위해 ES6/ES2015 적용 방법을 사용해야 한다.

참고자료 : https://jjeongil.tistory.com/949

 

시도

Math.max(array)

될 줄 알았다....

 

문제

프로그래머스 코딩테스트 입문 :  삼각형의 완성조건(1) (바로가기)

 

해결

function solution(sides) {
    let long = Math.max.apply(Math, sides)
    let sum = 0
    for(i=0;i<3;i++){
        sum += sides[i] 
    }
    if (long<sum-long){
        return 1
    } else{
        return 2
    }   
}

 

소감

스스로 해결할 수 있는 능력이 조금씩 늘고 있다.