如果要你用 JavaScript 寫一個 function 叫 repeat_words
repeat_words('a', 4); // output: 'aaaa'
你會怎麼寫呢?
通常第一個反應一定是用一個迴圈, 像這樣:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function repeat_word(str, n) { | |
var s = '' | |
for (i=0; i<n; i++) { | |
s += str; | |
} | |
return s; | |
} |
但有一種解法更快更簡單, 利用 Array 的 join, 有時候稍微轉個念, 就會衍生出更多方法了
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function repeat_word(str, n) { | |
return new Array(n+1).join(str); | |
} |