JavaScript - repeat()

isk·2022년 11월 6일

JavaScript

목록 보기
28/39

repeat() 메서드는 문자열을 주어진 횟수만큼 반복해 붙인 새로운 문자열을 반환한다.

구문 : str.repeat(count);

  • count
    문자열을 반복할 횟수. 0과 양의 무한대 사이의 정수([0, + ∞)).
'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

function result(string, n) {
    let a = string.split('')
    let b = a.repeat(n);
    
    return b;
}

a.repeat의 a가 배열이기 때문에 위 코드는 동작하지 않는다.

function result(string, n) {
    return string.split('').map(x => x.repeat(n)).join('');
}

그래서 map을 사용해서, x를 repeat한 값을 하나식 배열에 넣고 join으로 합쳐서 문자열로 만들어줬다.
map의 x는 배열 속 요소인 문자이기 때문에 실행이 가능하다.

0개의 댓글