透過遞迴構造字串 JavaScript


我們需要編寫一個遞迴函式,假設函式名稱為 pickString,該函式接受一個包含字母和數字組合的字串,並返回一個僅包含字母的新字串。

例如,

If the string is ‘dis122344as65t34er’,
The output will be: ‘disaster’

因此,我們來編寫這個遞迴函式的程式碼 −

示例

const str = 'ex3454am65p43le';
const pickString = (str, len = 0, res = '') => {
   if(len < str.length){
      const char = parseInt(str[len], 10) ? '' : str[len];
      return pickString(str, len+1, res+char);
   };
   return res;
};
console.log(pickString(str));
console.log(pickString('23123ca43n y43ou54 6do884 i43t'));
console.log(pickString('h432e54l43l65646o'));
console.log(pickString('t543h54is 54i5s 54t43he l543as53t
54ex87a455m54p45le'));

輸出

控制檯中的輸出將為 −

example
can you do it
hello
this is the last example

更新於: 25-Aug-2020

281 瀏覽

開啟您的 職業

完成課程後獲得認證

開始吧
廣告
© . All rights reserved.