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?