단어 s의 가운데 글자를 반환하는 함수, solution을 만들어 보세요. 단어의 길이가 짝수라면 가운데 두글자를 반환하면 됩니다.
s는 길이가 1 이상, 100이하인 스트링입니다.
값들을 하나하나 잘라주어 배열에 넣은 후, 배열 길이 / 2 한 값의 인덱스 번호에 위치한 값을 리턴하면 된다고 생각하였다.
다만, 길이가 짝수일 경우, 인덱스 번호-1 한 값도 함께 리턴해주었다. (인덱스 번호는 0부터 시작하기에)
💻 M Y C O D E 💻
function solution(s) { var answer = ""; const word = s.split(""); const centerNum = Math.floor(word.length/2); word.length%2 === 0 ? answer = word[centerNum-1]+word[centerNum] : answer = word[centerNum]; return answer; }
split()
메서드는 String 객체를 지정한 구분자를 이용하여 여러 개의 문자열로 나눈다.
const str = 'The quick brown fox jumps over the lazy dog.'; const words = str.split(' '); console.log(words[3]); // expected output: "fox" const chars = str.split(''); console.log(chars[8]); // expected output: "k" const strCopy = str.split(); console.log(strCopy); // expected output: Array ["The quick brown fox jumps over the lazy dog."]
Math.floor()
메서드는 주어진 숫자와 같거나 작은 정수 중에서 가장 큰 수를 반환한다.
console.log(Math.floor(5.95)); // expected output: 5 console.log(Math.floor(5.05)); // expected output: 5 console.log(Math.floor(5)); // expected output: 5 console.log(Math.floor(-5.05)); // expected output: -6
음수일 경우 원하는 값과 다를 수 있으니 주의하자
ex) -5.05 => 5가 아니라 -6임