Repeat String - Javascript

前端 未结 30 2458
长情又很酷
长情又很酷 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: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).

提交回复
热议问题