Repeat String - Javascript

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

    Note to new readers: This answer is old and and not terribly practical - it's just "clever" because it uses Array stuff to get String things done. When I wrote "less process" I definitely meant "less code" because, as others have noted in subsequent answers, it performs like a pig. So don't use it if speed matters to you.

    I'd put this function onto the String object directly. Instead of creating an array, filling it, and joining it with an empty char, just create an array of the proper length, and join it with your desired string. Same result, less process!

    String.prototype.repeat = function( num )
    {
        return new Array( num + 1 ).join( this );
    }
    
    alert( "string to repeat\n".repeat( 4 ) );
    

提交回复
热议问题