string.repeat

repeat() λ©”μ„œλ“œλŠ” 호좜된 λ¬Έμžμ—΄μ—μ„œ 사본이 포함. μ—°κ²°ν•˜μ—¬ μ§€μ •λœ 횟수의 μƒˆ λ¬Έμžμ—΄μ„ κ΅¬μ„±ν•˜κ³  λ°˜ν™˜ν•œλ‹€.

const str = 'κ³ μ–‘μ“° λ„ˆλ¬΄ κ·€μ—½μ“° ';

str.repeat(2); // "κ³ μ–‘μ“° λ„ˆλ¬΄ κ·€μ—½μ“° κ³ μ–‘μ“° λ„ˆλ¬΄ κ·€μ—½μ“° "

Syntax

str.repeat(count)

Parameters

count

λ¬Έμžμ—΄μ„ 반볡 ν•  횟수λ₯Ό λ‚˜νƒ€λ‚΄λŠ” 0κ³Ό +Infinity μ‚¬μ΄μ˜ μ •μˆ˜

Return value

μ£Όμ–΄μ§„ λ¬Έμžμ—΄μ˜ μ§€μ •λœ 수의 사본을 ν¬ν•¨ν•˜λŠ” μƒˆλ‘œμš΄ λ¬Έμžμ—΄

Exceptions

  • RangeError: 반볡 νšŸμˆ˜λŠ” μŒμˆ˜κ°€ μ•„λ‹ˆμ—¬μ•Ό ν•œλ‹€.

  • RangeError: 반볡 νšŸμˆ˜λŠ” λ¬΄ν•œλŒ€λ³΄λ‹€ μž‘μ•„μ•Όν•˜λ©° μ΅œλŒ€ λ¬Έμžμ—΄ 크기λ₯Ό λ„˜μ§€ μ•Šμ•„μ•Ό ν•œλ‹€.

Examples

'abc'.repeat(-1); // RangeError:  Invalid count value at String.repeat
'abc'.repeat(0); // ''
'abc'.repeat(1); // 'abc'
'abc'.repeat(2); // 'abcabc'
'abc'.repeat(3.5); // "abcabcabc" countλ₯Ό μ •μˆ˜λ‘œ λ³€ν™˜λ¨
'abc'.repeat(1/0); // RangeError: Invalid count value at String.repeat

({ toString: () => 'abc', repeat: String.prototype.repeat }).repeat(2); // "abcabc" repeat() generic method 이닀?

Polyfill

repeatλŠ” ECMAScript 2015 λͺ…세에 μΆ”κ°€λ˜μ—ˆλ‹€.

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 '';

    // countκ°€ 31λΉ„νŠΈ μ •μˆ˜μΈμ§€ ν™•μΈν•˜λ©΄ main partλ₯Ό 크게 μ΅œμ ν™” ν•  수 μžˆλ‹€. 
    // κ·ΈλŸ¬λ‚˜ λŒ€λΆ€λΆ„μ˜ μ΅œμ‹ (2014λ…„ 8μ›”) λΈŒλΌμš°μ €λŠ” λ¬Έμžμ—΄ 1 << 28 자 이상을 μ²˜λ¦¬ν•  수 μ—†μœΌλ―€λ‘œ 
    // λ‹€μŒκ³Ό 같이 ν•΄μ•Όν•œλ‹€.
    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;
  }
}

Browser compatibility

IE 놉 μ•ˆλ“œλ‘œμ΄λ“œ μ›Ήλ·° 놉

Last updated

Was this helpful?