String.prototype.repeat()
Метод repeat()
створює та повертає новий рядок, що містить вказану кількість об'єднаних разом копій рядка, на якому він був викликаний.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
Синтаксис
str.repeat(count)
Параметри
count
- Ціле число в діапазоні між
0
та+Infinity
, що вказує кількість повторів рядка.
Значення, що повертається
Новий рядок, що містить вказану кількість копій наданого рядка.
Винятки
RangeError
: число повторів має бути невід'ємним.RangeError
: число повторів має бути меншим за нескінченість та не перевищувати максимальний розмір рядка.
Приклади
'абв'.repeat(-1) // RangeError
'абв'.repeat(0) // ''
'абв'.repeat(1) // 'абв'
'абв'.repeat(2) // 'абвабв'
'абв'.repeat(3.5) // 'абвабвабв' (count буде перетворений на ціле число)
'абв'.repeat(1/0) // RangeError
({ toString: () => 'абв', repeat: String.prototype.repeat }).repeat(2)
// 'абвабв' (repeat() є загальним методом)
Поліфіл
Цей метод був доданий у специфікацію ECMAScript 2015 та може поки не бути доступним в усіх реалізаціях JavaScript. Однак, ви можете створити поліфіл String.prototype.repeat()
за допомогою наступного коду:
if (!String.prototype.repeat) {
String.prototype.repeat = function(count) {
'use strict';
if (this == null)
throw new TypeError('неможливо перетворити ' + this + ' на об\'єкт');
var str = '' + this;
// Щоб перетворити рядок на ціле число.
count = +count;
// Перевірка на NaN
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-бітним числом, дозволяє значно оптимізувати
// головну частину. Але, все ж, найновіші (серпень 2014) переглядачі не можуть
// впоратись з рядками з 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;
}
}
Специфікації
Специфікація |
---|
ECMAScript (ECMA-262) The definition of 'String.prototype.repeat' in that specification. |
Сумісність з веб-переглядачами
BCD tables only load in the browser
The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.