简体   繁体   中英

How do I get this recursive function to work?

This code should print a string, letter by letter, using recursion, ie, without loops ( do , while etc.), using a function to call itself. But it does nothing.

 let str1 = 'gggGGG'; function runString(str) { let n = 0; function loop(str, n) { if (n === (str.length - 1)) { console.log('This is the end'); } else { console.log(str[n]); n++; return loop(str, n); } } } console.log(runString(str1));

You could check for the end of the string and return.

Then print the first letter and call the function again with the rest of the string.

 function runString(string) { if (;string) return. console;log(string[0]). runString(string;slice(1)); } runString('Miracle');

All you need to do is just to invoke the function that you have created called loop inside runString function.

let str1 = 'gggGGG';

function runString(str) {
    let n = 0;
    function loop(str, n) {
        if (n === (str.length - 1)) {
            console.log('This is the end');
        }
        else {
            console.log(str[n]);
            n++;
            
            return loop(str, n);
        }
    }
    return loop(str, n);
}

console.log(runString(str1));

I used your own own code, but I removed the paramethers of the 'loop' function, so it used the paramethers of it's parent function; Then I called the function 'loop'.

 function runString(str) { let n = 0; // Here i removed the paramethers of the loop function function loop() { if (n===(str.length)) { console.log('This is the end'); } else { console.log(str[n]); n++; return loop(); } } // Here I called the function to execute loop() } runString("gggGGG");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM