str.repeat(count);
function solution(my_string, k) {
let answer = ''
for(let i=0; i<k; i++){
answer += my_string;
}
return answer
}
for문 말고 어떻게 하면 코드를 간결하게 할 수 있을까 고민해봤는데, 아무리 생각해봐도 생각이 나질 않아 일단 for문을로 돌려서 제출하고 다른 사람의 코드를 봤다.
function solution(my_string, k) {
return my_string.repeat(k)
}
맙소사....... repeat는 처음 보는 것이었다.
repeat
repeat는 문자열 반복 함수로, 문자열을 주어진 횟수만큼 반복해 붙인 새로운 문자열을 반환한다.
str.repeat(count);
위와 같이 쓰이며 예제는 아래와 같다.
"abc".repeat(-1); // RangeError
"abc".repeat(0); // ''
"abc".repeat(1); // 'abc'
"abc".repeat(2); // 'abcabc'
"abc".repeat(3.5); // 'abcabcabc' (count will be converted to integer)
"abc".repeat(1 / 0); // RangeError
({ toString: () => "abc", repeat: String.prototype.repeat }).repeat(2);
// 'abcabc' (repeat() is a generic method)
'코테' 카테고리의 다른 글
두 수의 연산값 비교하기 (0) | 2024.11.29 |
---|---|
더 크게 합치기 (0) | 2024.11.29 |
문자 리스트를 문자열로 변환하기 (0) | 2024.11.29 |
문자열 섞기 (0) | 2024.11.29 |
문자열 겹쳐쓰기 (0) | 2024.11.28 |