Repeat Character N Times

后端 未结 23 2496
栀梦
栀梦 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:16
    String.prototype.repeat = function (n) { n = Math.abs(n) || 1; return Array(n + 1).join(this || ''); };
    
    // console.log("0".repeat(3) , "0".repeat(-3))
    // return: "000" "000"
    
    0 讨论(0)
  • 2020-11-22 12:19

    In CoffeeScript:

    ( 'a' for dot in [0..10]).join('')
    
    0 讨论(0)
  • 2020-11-22 12:20

    Another interesting way to quickly repeat n character is to use idea from quick exponentiation algorithm:

    var repeatString = function(string, n) {
        var result = '', i;
    
        for (i = 1; i <= n; i *= 2) {
            if ((n & i) === i) {
                result += string;
            }
            string = string + string;
        }
    
        return result;
    };
    
    0 讨论(0)
  • 2020-11-22 12:20

    Here is an ES6 version

    const repeat = (a,n) => Array(n).join(a+"|$|").split("|$|");
    repeat("A",20).forEach((a,b) => console.log(a,b+1))

    0 讨论(0)
  • 2020-11-22 12:21

    In ES2015/ES6 you can use "*".repeat(n)

    So just add this to your projects, and your are good to go.

      String.prototype.repeat = String.prototype.repeat || 
        function(n) {
          if (n < 0) throw new RangeError("invalid count value");
          if (n == 0) return "";
          return new Array(n + 1).join(this.toString()) 
        };
    
    0 讨论(0)
  • 2020-11-22 12:22

    Lodash offers a similar functionality as the Javascript repeat() function which is not available in all browers. It is called _.repeat and available since version 3.0.0:

    _.repeat('a', 10);
    
    0 讨论(0)
提交回复
热议问题