728x90

repeat() 메서드는 문자열을 주어진 매개변수의 횟수만큼 반복하여 붙인 새로운 문자열을 반환합니다.

구문

str.repeat(count);

매개변수

count - 문자열을 반복할 횟수. 0과 양의 무한대 사이의 정수 ([0, +∞))

리턴값

현재 문자열을 주어진 매개변수의 횟수만큼 반복해 붙인 새로운 문자열.

예제

const str = '안녕하세요';

str.repeat(-1);
// RangeError

str.repeat(0);
// ''

str.repeat(1);
// 안녕하세요

str.repeat(2);
// 안녕하세요안녕하세요

str.repeat(3.5);
// 안녕하세요안녕하세요 (카운트는 정수형으로 변환되어 적용)

str.repeat(1/0); 
// RangeError (infinity)

repeat은 ECMAScript 2015 명세에 추가 되었으므로, 어떠한 표준 구현체에서는 사용할 수 없을 수 있습니다.

아래 코드를 포함하면 미지원 플랫폼에서도 repeat을 사용할 수 있습니다.

if (!String.prototype.repeat) {
  String.prototype.repeat = function(count) {
    'use strict';
    if (this == null) {
      throw new TypeError('can\'t convert ' + this + ' to object');
    }
    var str = '' + this;
    count = +count;
    if (count != count) {
      count = 0;
    }
    if (count < 0) {
      throw new RangeError('repeat count must be non-negative');
    }
    if (count == Infinity) {
      throw new RangeError('repeat count must be less than infinity');
    }
    count = Math.floor(count);
    if (str.length == 0 || count == 0) {
      return '';
    }
    // Ensuring count is a 31-bit integer allows us to heavily optimize the
    // main part. But anyway, most current (August 2014) browsers can't handle
    // strings 1 << 28 chars or longer, so:
    if (str.length * count >= 1 << 28) {
      throw new RangeError('repeat count must not overflow maximum string size');
    }
    var maxCount = str.length * count;
    count = Math.floor(Math.log(count) / Math.log(2));
    while (count) {
       str += str;
       count--;
    }
    str += str.substring(0, maxCount - str.length);
    return str;
  }
}

 

출처: https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/repeat

728x90

+ Recent posts