Repeat String - Javascript

前端 未结 30 1820
长情又很酷
长情又很酷 2020-11-22 08:46

What is the best or most concise method for returning a string repeated an arbitrary amount of times?

The following is my best shot so far:

function          


        
相关标签:
30条回答
  • 2020-11-22 09:13

    Use Lodash for Javascript utility functionality, like repeating strings.

    Lodash provides nice performance and ECMAScript compatibility.

    I highly recommend it for UI development and it works well server side, too.

    Here's how to repeat the string "yo" 2 times using Lodash:

    > _.repeat('yo', 2)
    "yoyo"
    
    0 讨论(0)
  • 2020-11-22 09:14

    This one is pretty efficient

    String.prototype.repeat = function(times){
        var result="";
        var pattern=this;
        while (times > 0) {
            if (times&1)
                result+=pattern;
            times>>=1;
            pattern+=pattern;
        }
        return result;
    };
    
    0 讨论(0)
  • 2020-11-22 09:16

    Here's a 5-7% improvement on disfated's answer.

    Unroll the loop by stopping at count > 1 and perform an additional result += pattnern concat after the loop. This will avoid the loops final previously unused pattern += pattern without having to use an expensive if-check. The final result would look like this:

    String.prototype.repeat = function(count) {
        if (count < 1) return '';
        var result = '', pattern = this.valueOf();
        while (count > 1) {
            if (count & 1) result += pattern;
            count >>= 1, pattern += pattern;
        }
        result += pattern;
        return result;
    };
    

    And here's disfated's fiddle forked for the unrolled version: http://jsfiddle.net/wsdfg/

    0 讨论(0)
  • 2020-11-22 09:16

    Simple method:

    String.prototype.repeat = function(num) {
        num = parseInt(num);
        if (num < 0) return '';
        return new Array(num + 1).join(this);
    }
    
    0 讨论(0)
  • 2020-11-22 09:18
    function repeat(s, n) { var r=""; for (var a=0;a<n;a++) r+=s; return r;}
    
    0 讨论(0)
  • 2020-11-22 09:18
    function repeat(pattern, count) {
      for (var result = '';;) {
        if (count & 1) {
          result += pattern;
        }
        if (count >>= 1) {
          pattern += pattern;
        } else {
          return result;
        }
      }
    }
    

    You can test it at JSFiddle. Benchmarked against the hacky Array.join and mine is, roughly speaking, 10 (Chrome) to 100 (Safari) to 200 (Firefox) times faster (depending on the browser).

    0 讨论(0)
提交回复
热议问题