Repeat String - Javascript

前端 未结 30 2217
长情又很酷
长情又很酷 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条回答
  •  萌比男神i
    2020-11-22 09:11

    For all browsers

    This is about as concise as it gets :

    function repeat(s, n) { return new Array(n+1).join(s); }
    

    If you also care about performance, this is a much better approach :

    function repeat(s, n) { var a=[],i=0;for(;i

    If you want to compare the performance of both options, see this Fiddle and this Fiddle for benchmark tests. During my own tests, the second option was about 2 times faster in Firefox and about 4 times faster in Chrome!

    For moderns browsers only :

    In modern browsers, you can now also do this :

    function repeat(s,n) { return s.repeat(n) };
    

    This option is not only shorter than both other options, but it's even faster than the second option.

    Unfortunately, it doesn't work in any version of Internet explorer. The numbers in the table specify the first browser version that fully supports the method :

提交回复
热议问题