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 September 2015.
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 将被转换为整数)
"abc".repeat(1 / 0); // RangeError
({ toString: () => "abc", repeat: String.prototype.repeat }).repeat(2);
// 'abcabc'(repeat() 是一个通用方法)
规范
Specification |
---|
ECMAScript® 2025 Language Specification # sec-string.prototype.repeat |
浏览器兼容性
BCD tables only load in the browser