String.prototype.repeat()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. Itâs been available across browsers since 2015ë 9ì.
repeat() ë©ìëë 문ìì´ì 주ì´ì§ íìë§í¼ ë°ë³µí´ ë¶ì¸ ìë¡ì´ 문ìì´ì ë°íí©ëë¤.
구문
js
str.repeat(count);
매ê°ë³ì
count-
문ìì´ì ë°ë³µí íì. 0ê³¼ ìì 무íë ì¬ì´ì ì ì([0, +â)).
ë°íê°
íì¬ ë¬¸ìì´ì 주ì´ì§ íìë§í¼ ë°ë³µí´ ë¶ì¸ ìë¡ì´ 문ìì´.
ìì¸
RangeError: ë°ë³µ íìë ìì ì ìì¬ì¼ í¨.RangeError: ë°ë³µ íìë 무íëë³´ë¤ ììì¼ íë©°, ìµë 문ìì´ í¬ê¸°ë¥¼ ëì´ì ìë¨.
ìì
js
"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
({ toString: () => "abc", repeat: String.prototype.repeat }).repeat(2);
// 'abcabc' (repeat() is a generic method)
í´ë¦¬í
repeatì ECMAScript 2015 ëª
ì¸ì ì¶ê°ëìµëë¤. ë°ë¼ì ì´ë¤ íì¤ êµ¬íì²´ììë ì¬ì©í ì ìì ìë ììµëë¤. ê·¸ë¬ë ìë ì½ë를 í¬í¨íë©´ ì§ìíì§ ìë íë«í¼ììë repeatì ì¬ì©í ì ììµëë¤.
js
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;
};
}
ëª ì¸
| Specification |
|---|
| ECMAScript® 2027 Language Specification> # sec-string.prototype.repeat> |