--- title: String.prototype.repeat() slug: Web/JavaScript/Reference/Global_Objects/String/repeat tags: - Chuỗi - ES6 - Phương Thức - Tham khảo translation_of: Web/JavaScript/Reference/Global_Objects/String/repeat ---
Phương thức repeat()
xây dựng và trả về một chuỗi mới chứa số lượng nhất định bản sao chép của chuỗi được gọi tới và nối chung với nhau.
str.repeat(count);
count
Một chuỗi mới chứa số lần sao chép (count) chuỗi đầu vào.
'abc'.repeat(-1); // RangeError 'abc'.repeat(0); // '' 'abc'.repeat(1); // 'abc' 'abc'.repeat(2); // 'abcabc' 'abc'.repeat(3.5); // 'abcabcabc' (tham số đếm sẽ được chuyển thành số nguyên) 'abc'.repeat(1/0); // RangeError ({ toString: () => 'abc', repeat: String.prototype.repeat }).repeat(2); // 'abcabc' (repeat() is a generic method)
Phương thức này đã được thêm vào kỹ thuật ES6 và có thể chưa có sẵn trong tất cả các bản bổ sung JS. Tuy nhiên bạn có thể sử dụng polyfill String.prototype.repeat()
với snippet dưới đây:
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 ''; } // Đảm bảo tham số đếm là số nguyên 31 bít cho phép ta tối ưu hóa nhiều // phần chính. Nhưng dù sao thì, hầu hết các trình duyệt hiện tại (tháng Tám năm 2014) không thể xử lý // các chuỗi 1 << 28 chars hoặc lớn hơn, vậy nên: 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 | Status | Comment |
---|---|---|
{{SpecName('ES2015', '#sec-string.prototype.repeat', 'String.prototype.repeat')}} | {{Spec2('ES2015')}} | Định nghĩa bổ sung. |
{{SpecName('ESDraft', '#sec-string.prototype.repeat', 'String.prototype.repeat')}} | {{Spec2('ESDraft')}} |
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.
{{Compat("javascript.builtins.String.repeat")}}