Repeat String - Javascript

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

    ES2015 has been realized this repeat() method!

    http://www.ecma-international.org/ecma-262/6.0/#sec-string.prototype.repeat
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat
    http://www.w3schools.com/jsref/jsref_repeat.asp

    /** 
     * str: String
     * count: Number
     */
    const str = `hello repeat!\n`, count = 3;
    
    let resultString = str.repeat(count);
    
    console.log(`resultString = \n${resultString}`);
    /*
    resultString = 
    hello repeat!
    hello repeat!
    hello repeat!
    */
    
    ({ toString: () => 'abc', repeat: String.prototype.repeat }).repeat(2);
    // 'abcabc' (repeat() is a generic method)
    
    // Examples
    
    'abc'.repeat(0);    // ''
    'abc'.repeat(1);    // 'abc'
    'abc'.repeat(2);    // 'abcabc'
    'abc'.repeat(3.5);  // 'abcabcabc' (count will be converted to integer)
    // 'abc'.repeat(1/0);  // RangeError
    // 'abc'.repeat(-1);   // RangeError

提交回复
热议问题