Repeat a given string (first argument) num times (second argument). Return an empty string if num is not a positive number.
TEST
repeatStringNumTimes("", 3) should return "*".
repeatStringNumTimes("abc", 3) should return "abcabcabc".
repeatStringNumTimes("abc", 4) should return "abcabcabcabc".
repeatStringNumTimes("abc", 1) should return "abc".
repeatStringNumTimes("", 8) should return "********".
repeatStringNumTimes("abc", -2) should return "".
!问题:数组与字符一些方法弄混
//方法1
function repeatStringNumTimes(str, num) {
var newStr = '';
while(num>0){
newStr += str;
num--;
}
return newStr;
}
console.log(repeatStringNumTimes("abc", 3));```
##??return str + repeatStringNumTimes(str,num-1);能不能直接修改为repeatStringNumTimes(str,num);??
//方法2:递归
function repeatStringNumTimes(str,num){
if(num<0)
return '';
if(num===1)
return str;
else
return str + repeatStringNumTimes(str,num-1);
}
console.log(repeatStringNumTimes("abc", 3));```
//方法3: str.repeat()
function repeatStringNumTimes(str,num){
return num > 0 ? str.repeat(num) : '';
}
console.log(repeatStringNumTimes("abc", 3));```