Repeat Character N Times

后端 未结 23 2503
栀梦
栀梦 2020-11-22 11:51

In Perl I can repeat a character multiple times using the syntax:

$a = \"a\" x 10; // results in \"aaaaaaaaaa\"

Is there a simple way to ac

23条回答
  •  清酒与你
    2020-11-22 12:27

    /**  
     * Repeat a string `n`-times (recursive)
     * @param {String} s - The string you want to repeat.
     * @param {Number} n - The times to repeat the string.
     * @param {String} d - A delimiter between each string.
     */
    
    var repeat = function (s, n, d) {
        return --n ? s + (d || "") + repeat(s, n, d) : "" + s;
    };
    
    var foo = "foo";
    console.log(
        "%s\n%s\n%s\n%s",
    
        repeat(foo),        // "foo"
        repeat(foo, 2),     // "foofoo"
        repeat(foo, "2"),   // "foofoo"
        repeat(foo, 2, "-") // "foo-foo"
    );
    

提交回复
热议问题