Repeat String - Javascript

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

    To repeat a string in a specified number of times, we can use the built-in repeat() method in JavaScript.

    Here is an example that repeats the following string for 4 times:

    const name = "king";
    
    const repeat = name.repeat(4);
    
    console.log(repeat);
    

    Output:

    "kingkingkingking"
    

    or we can create our own verison of repeat() function like this:

    function repeat(str, n) {
      if (!str || !n) {
        return;
      }
    
     let final = "";
      while (n) {
        final += s;
        n--;
      }
      return final;
    }
    
    console.log(repeat("king", 3))
    

    (originally posted at https://reactgo.com/javascript-repeat-string/)

提交回复
热议问题