String.prototype.repeat()
String 对象的 repeat() 方法创建一个新的字符串,该字符串包含指定数量的当前字符串的副本,这些副本已连接在一起。
试一试
const mood = "Happy! ";
console.log(`I feel ${mood.repeat(3)}`);
// Expected output: "I feel Happy! Happy! Happy! "
语法
js
repeat(count)
参数
返回值
一个包含指定数量的给定字符串副本的新字符串。
异常
RangeError-
如果
count为负数或count超过最大字符串长度,则会抛出错误。
示例
使用 repeat()
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)
规范
| 规范 |
|---|
| ECMAScript® 2026 语言规范 # sec-string.prototype.repeat |
浏览器兼容性
加载中…