Seen some solutions using a regular for loop, but was interested in the recursive way
maybe we can define the arr as the alphabet
let arr = ['abcdefghij(...rest_of_alphabet)`]
found this on the interwebs, would this work?
Call map() using the array [ ‘a’, ‘b’, ‘c’ ] Create a new array that holds the result of calling fn(‘a’) Return [ ‘A’ ].concat( map([ ‘b’, ‘c’ ]) ) Repeat steps 1 through 3 with [ ‘b’, ‘c’ ] Repeat steps 1 through 3 for [ ‘c’ ] Eventually, we call map() with an empty array, which ends the recursion.
CodePudding user response:
Here is a way:
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);
CodePudding user response:
A simplification of this answer, without the array:
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();