Repeat String - Javascript

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

    Expanding P.Bailey's solution:

    String.prototype.repeat = function(num) {
        return new Array(isNaN(num)? 1 : ++num).join(this);
        }
    

    This way you should be safe from unexpected argument types:

    var foo = 'bar';
    alert(foo.repeat(3));              // Will work, "barbarbar"
    alert(foo.repeat('3'));            // Same as above
    alert(foo.repeat(true));           // Same as foo.repeat(1)
    
    alert(foo.repeat(0));              // This and all the following return an empty
    alert(foo.repeat(false));          // string while not causing an exception
    alert(foo.repeat(null));
    alert(foo.repeat(undefined));
    alert(foo.repeat({}));             // Object
    alert(foo.repeat(function () {})); // Function
    

    EDIT: Credits to jerone for his elegant ++num idea!

提交回复
热议问题