[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/String/repeat [Back]  [Original]

String.prototype.repeat() - JavaScript | MDN

This page was translated from English by the community. Learn more and join the MDN Web Docs community.

View in English Always switch to English

String.prototype.repeat()

Baseline
Widely available

This feature is well established and works across many devices and browser versions. Its been available across browsers since 2015 ..

repeat() , , .

In this article

str.repeat(count)

count

0 +: [0, +), .

, , .

js
"".repeat(-1); // RangeError
"".repeat(0); // ''
"".repeat(1); // ''
"".repeat(2); // ''
"".repeat(3.5); // '' (     )
"".repeat(1 / 0); // RangeError

({ toString: () => "", repeat: String.prototype.repeat }).repeat(2);
// '' ( repeat()   )

ECMAScript 2015 JavaScript. , :

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 "";
    }
    //  ,  count  31-  ,   
    //    . ,   ( 
    // 2014 )    ,  1 << 28 ,  :
    if (str.length * count >= 1 << 28) {
      throw new RangeError(
        "repeat count must not overflow maximum string size",
      );
    }
    var rpt = "";
    for (var i = 0; i < count; i++) {
      rpt += str;
    }
    return rpt;
  };
}

Specification
ECMAScript 2027 LanguageSpecification
# sec-string.prototype.repeat


Web Proxy Viewer  |  New URL  |  Original Page