給出字符串和重複次數,返回重複屢次的字符串code
repeatStringNumTimes("abc", 3) repeatStringNumTimes("abc", -2) should return "".
while循環遞歸
num控制循環次數ip
function repeatStringNumTimes(str,num) { var newstr = ''; while(num>0) { newstr += str; num--; } return newstr; } repeatStringNumTimes("abc", 3);
str.repeat()方法字符串
//寫法1 function repeatStringNumTimes(str,num) { if(num>0) { return str.repeat(num); } return ""; } //寫法2 function repeatStringNumTimes(str,num) { return num > 0 ? str.repeat(num) : ""; } repeatStringNumTimes("abc", 3);
if語句get
遞歸io
function repeatStringNumTimes(str,num) { if(num<0) { return ""; } else if(num=0|1) { return str } else { return str + repeatStringNumTimes(str,num-1); } } repeatStringNumTimes("abc", 3);
let resultString = str.repeat(count);
repeat() 構造並返回一個新字符串,該字符串包含被鏈接在一塊兒的指定數量的字符串的副本function
遞歸循環