Повторите строку - JavaScript

Я использую Munin и Monit и был очень доволен ими обоими.

266
задан brad 14 October 2008 в 09:10
поделиться

2 ответа

/**  
@desc: repeat string  
@param: n - times  
@param: d - delimiter  
*/

String.prototype.repeat = function (n, d) {
    return --n ? this + (d || '') + this.repeat(n, d) : '' + this
};

так можно повторить строку несколько раз с использованием разделителя.

5
ответ дан 23 November 2019 в 02:24
поделиться

Расширяя решение P.Bailey:

String.prototype.repeat = function(num) {
    return new Array(isNaN(num)? 1 : ++num).join(this);
    }

Так вы обезопасите себя от неожиданных типов аргументов:

var foo = 'bar';
alert(foo.repeat(3));              // Will work, "barbarbar"
alert(foo.repeat('3'));            // Same as above
alert(foo.repeat(true));           // Same as foo.repeat(1)

alert(foo.repeat(0));              // This and all the following return an empty
alert(foo.repeat(false));          // string while not causing an exception
alert(foo.repeat(null));
alert(foo.repeat(undefined));
alert(foo.repeat({}));             // Object
alert(foo.repeat(function () {})); // Function

EDIT: Благодарность jerone за его элегантную ++num идею!

17
ответ дан 23 November 2019 в 02:24
поделиться
Другие вопросы по тегам:

Похожие вопросы: