Repeat String - Javascript

前端 未结 30 2438
长情又很酷
长情又很酷 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:04

    People overcomplicate this to a ridiculous extent or waste performance. Arrays? Recursion? You've got to be kidding me.

    function repeat (string, times) {
      var result = ''
      while (times-- > 0) result += string
      return result
    }
    

    Edit. I ran some simple tests to compare with the bitwise version posted by artistoex / disfated and a bunch of other people. The latter was only marginally faster, but orders of magnitude more memory-efficient. For 1000000 repeats of the word 'blah', the Node process went up to 46 megabytes with the simple concatenation algorithm (above), but only 5.5 megabytes with the logarithmic algorithm. The latter is definitely the way to go. Reposting it for the sake of clarity:

    function repeat (string, times) {
      var result = ''
      while (times > 0) {
        if (times & 1) result += string
        times >>= 1
        string += string
      }
      return result
    }
    

提交回复
热议问题