Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

javascript - Converting a loop into a recursive function

I wrote a function yesterday to count the number of "a" characters in a string. My teacher told me to refactor the code into a recursive function and I don't really know how to do so.

I would like some feedback on the subject, and by the way I'm an absolute beginner in JavaScript.

function numberOfA(n){
var numberA =0;

for (i=0; i<=n.length; i++){

    if(n.charAt(i)== "a"  ){
        numberA++;}
    }
return numberA;

}

to call the function following piece of code :

var n = prompt("type a word");
var output = numberOfA(n);

alert (output);

Thanks in advance !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The goal of recursion is to make a function which calls itself.
You might have mutual-recursion -- function A calls function B, calls function A... but that's certainly not needed here, and is better suited for when you know that you need to do two distinct things (one per function) and know that you need to do them in a leapfrog pattern.

Where recursion comes into play is when you're thinking about loops.
Normally, when you're doing things with loops, you might end up having two or three loops inside of one another.
Instead of worrying about managing loops, recursion is a way of thinking about what happens in a single-iteration of a loop, and writing ONLY the code needed to do that.

A really simple example of singular recursion might be to log all elements of an array to the console.
This is not a practical example -- it's a trivial example which has most of the pieces you need to make practical examples.

var array = [ "one", "two", "three", "four" ];

function listNextItem (array, index) {
    var item = array[index];
    if (!item) { return; }

    console.log(item);
    listNextItem(array, index + 1);
}

listNextItem(array, 0);

I've created a very simple function which looks like the inside of your innermost loop.
It sets an item variable, based on array[index].
If it doesn't exist, we're done, and we can return out of the function, so we don't try to go on forever (this is very important in recursion).

If it does exist, we log the item's value. Then we call the exact same function, and pass it the exact-same array, but we pass it the value of index + 1.

Did this change anybody's life, or make loops obsolete?
Not really.

But it's the first step to getting recursion.

The next step is getting a return from recursion.

function recursiveAddOne (current, max) {
    if (current === max) { return current; }
    return 1 + recursiveAddOne(current + 1, max);
}

var total = recursiveAddOne(0, 3); // === 3 + 1 + 1 + 1
total; // 6

Normally in my return statement, I'd be sending the answer back to the variable in the outside world.
I'm still doing that, but here I'm adding a call to the same function, as part of my return.

What does that do?
Well, the outside function can't return a value until the inside function returns.
The inside function can't return a value until ITS inside function returns...

...and it goes all the way down until my termination-condition is met. That condition returns a value to its outer function. That outer function returns that added value to ITS outer function... ...all the way up to where the outermost function gets handed the value of all of the other functions put together, and then returns THAT to the outside world.

It's like giving each Russian Matryoshka ("babushka") doll a piece of work.
You start with the biggest one, and go all the way inside to the tiniest one.
The tiniest one does its work first, and hands it back to the next one, which does its work and hands that back... ...all the way back until you're outside again.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...