차례대로 문자열 3개를 입력받아, 가장 짧은 문자열을 리턴해야 합니다.
string
타입의 문자열word1.length
는 10 이하string
타입의 문자열word2.length
는 10 이하string
타입의 문자열word3.length
는 10 이하string
타입을 리턴해야 합니다.let output = findShortestOfThreeWords('a', 'two', 'three');
console.log(output); // --> 'a'
output = findShortestOfThreeWords('c', 'b', 'a');
console.log(output); // --> 'c'
function Shortest(word1, word2, word3) {
/*
1 word2 보다 word1이 더 길때
1-1 word 2 랑 word 3을 비교
2 word1 과 word3 을 비교
*/
let short = word1
if(word1.length > word2.length){
short = word2; // 조건 1
if(word2.length > word3.length)
short = word3 // 조건 2
}else{
if(word1.length > word3.length){
short = word3;
}
}
return short
}
숫자 세개를 비교하는 알고리즘
가장 짧은 단어를 word1로 지정해두고
word1과 2를 비교한뒤 3과도 비교해주고
1과 3을 비교해주면 전체 다 비교해주게 된다
중첩 if문의 개념을 확실하게 알게 되었던 문제다
위의 코드를 보면 조건1을 만족해야 조건2로 넘어가게된다
조건 1을 틀릴경우 조건 2는 실행되지 않는다
2개 이상의 변수중 큰 값 찾기
let a = 5, b = 6, c =,7;
let max = Math.max(a,b,c);
2개 이상의 변수 중 가장 작은 값 찾기
let a = 5, b = 6, c = 6;
let min = Math.min(a,b,c);
배열 내 숫자 중 가장 큰 값 찾기
let arr = [5, 6, 7];
let max = Math.max.apply(null, arr);
배열 내 숫자 중 가장 작은 값 찾기
let arr = [5, 6, 7];
let min = Math.min.apply(null, arr);
주의해야 할 것은 배열 내에 비교 불가능한 값이 있다면 결과는 NaN으로 나온다
slice 와 sort를 사용한 방법도 있다
var min = [1, 5, 2, 3].slice(0).sort(function(a,b){a>b})[0];
var max = [1, 5, 2, 3].slice(0).sort(function(a,b){a<b})[0];
["b","a","d","c"].slice(0).sort()[0]; //"a"
["b","a","d","c"].slice(0).sort().reverse()[0]; //"d"
["b","a","d","c"].slice(0).sort(function(a,b){return a > b;})[0]; //"a"
["b","a","d","c"].slice(0).sort(function(a,b){return a < b;})[0]; //"d"