JavaScript 中 n 次運球字串


我們需要編寫一個 JavaScript 函式,該函式接收一個字串和一個數字 n 作為輸入,函式應該返回一個新字串,其中原始字串的所有字母重複 n 次。

例如:如果字串是 -

const str = 'how are you'

並且數字 n 是 2。

輸出

那麼輸出應該為 -

const output = 'hhooww aarree yyoouu'

因此,讓我們為該函式編寫程式碼 -

示例

程式碼如下 -

const str = 'how are you';
const repeatNTimes = (str, n) => {
   let res = '';
   for(let i = 0; i < str.length; i++){
      // using the String.prototype.repeat() function
      res += str[i].repeat(n);
   };
   return res;
};
console.log(repeatNTimes(str, 2));

控制檯中的輸出將為 -

hhooww aarree yyoouu

更新於: 2020-10-17

69 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.