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 |
瀏覽器相容性
載入中…