簡體   English   中英

如何遞歸打印 Javascript 中的字母表?

[英]How to recursively print the alphabet in Javascript?

看到一些使用常規 for 循環的解決方案,但對遞歸方式感興趣

也許我們可以將 arr 定義為字母表

let arr = ['abcdefghij(...rest_of_alphabet)`]

在網上找到了這個,這個有用嗎?

使用數組調用 map() [ 'a', 'b', 'c' ] 創建一個保存調用 fn('a') 的結果的新數組 Return [ 'A' ].concat( map([ 'b ', 'c' ]) ) 使用 [ 'b', 'c' ] 重復步驟 1 到 3 .

這是使用單個charCode參數的簡單遞歸技術 -

 const alphabet = (charCode = 97) => charCode > 122? "": String.fromCharCode(charCode) + alphabet(charCode + 1) console.log(alphabet()) // abcdefghijklmnopqrstuvwxyz

注意 exit charCode 被硬編碼為122 我們將通過輸出通用charRange來使 function 更加靈活,其中調用者指定范圍的開始和結束 -

 const charRange = (min, max) => min > max? "": String.fromCharCode(min) + charRange(min + 1, max) console.log(charRange(97, 122)) // abcdefghijklmnopqrstuvwxyz console.log(charRange(65, 90)) // ABCDEFGHIJKLMNOPQRSTUVWXYZ

這是一種方法:

 const alphabet = Array.from({length: 26}, (x, i) => String.fromCharCode(97 + i)); function printEach(arr) { if (arr.length === 0) return; // If arr is empty, return console.log(arr.shift()); // Remove the first letter from arr and print it return printEach(arr); // Deal with the remaining elements } printEach(alphabet);

這個答案的簡化,沒有數組:

 function printAlphabet (codePoint = 97) { if (codePoint > 122) return; // If code point is greater than "z" console.log(String.fromCodePoint(codePoint)); return printAlphabet(codePoint + 1); } printAlphabet();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM