Javascript初學筆記8 顛倒字串的三種作法

在AC之前的作業有一份是需要顛倒輸入的字串,當時使用的語言是Ruby,突發奇想在JS中應該怎麼去做? 在此做個紀錄。

Built-In function(split,reverse,join)

 const reversestring = (word) => {
let word_split = word.split('')//令輸入的字串轉為陣列
let reverse_array = word_split.reverse() //反轉輸入的陣列
let join_array = reverse_array.join('') //連接反轉的陣列
return join_array
}
console.log(reversestring('hello')) //olleh

概念了解後,便可精簡為以下的作法

function reverseString(str) {

return str.split("").reverse().join("");

}

reverseString("hello");

For loop(遞減)

 const reversestring = (word) => {
let empty = ''
for (let i = word.length -1 ; i >= 0; i-- ){
empty += word[i]
}
return empty
}
reversestring('hello')

**遞迴( Recursion ) 配合 substr() 以及 charAt() 兩個方法

這個做法我完全沒想到,附上參考文章的連結

https://medium.freecodecamp.org/how-to-reverse-a-string-in-javascript-in-3-different-ways-75e4763c68cb

首先先針對substr() & charAt()兩種方法說明
substr(x)會從index x開始做字串的擷取 例如 ‘hello’.substr(1) // ello
charAt(x)則會回傳指定index的字元 例如 ‘hello’.charAt(0) //h

  function reverseString(str) {

if (str === "") // This is the terminal case that will end the recursion

return "";



else

return reverseString(str.substr(1)) + str.charAt(0);

這個部分對初學的我來說真的很複雜,我先附上原始的解釋

 
function reverseString(str) {

if (str === "") // This is the terminal case that will end the recursion

return "";



else

return reverseString(str.substr(1)) + str.charAt(0);

/*

First Part of the recursion method

You need to remember that you won’t have just one call, you’ll have several nested calls



Each call: str === "?" reverseString(str.subst(1)) + str.charAt(0)

1st call – reverseString("Hello") will return reverseString("ello") + "h"

2nd call – reverseString("ello") will return reverseString("llo") + "e"

3rd call – reverseString("llo") will return reverseString("lo") + "l"

4th call – reverseString("lo") will return reverseString("o") + "l"

5th call – reverseString("o") will return reverseString("") + "o"



Second part of the recursion method

The method hits the if condition and the most highly nested call returns immediately



5th call will return reverseString("") + "o" = "o"

4th call will return reverseString("o") + "l" = "o" + "l"

3rd call will return reverseString("lo") + "l" = "o" + "l" + "l"

2nd call will return reverserString("llo") + "e" = "o" + "l" + "l" + "e"

1st call will return reverserString("ello") + "h" = "o" + "l" + "l" + "e" + "h"

*/

}

reverseString("hello");

乍看之下可能很複雜,其實理解了之後就會覺得很簡單。
大致上的意思是這樣的,總共會跑五次遞迴,每一次取出的都會是最後一個字元,而每次的遞迴都會再次呼叫函數本身,所以其實最後return的東西應該是像以下這樣
第五次call + ‘o’ + 第四次call + ‘l’ +第三次call + ‘l’ + 第二次call + ‘e’ +第一次call + ‘h’
第一次call反而會被擠到最後面,從而實現反轉字串的函數,這還真的很有趣~!

發表留言