2016年3月18日 星期五

Javascript basic algorithm(8)--Repeat a string repeat a string

Repeat a string

Review: Global string Object, while vs for;

Solution 1:

  thinking process:
      1. create a variable to store a new string.
      2. create a loop to repeat as many times as needed
      3. make the variable created store the current value and append the word to it.

  Code:

function repeat(str, num) {
    var accumulatedStr = "";
    while (num > 0) {
        accumulatedStr += str;
        num--;
    }
    return accumulatedStr;
}


Reference:  Here

沒有留言:

張貼留言