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?