Why Is My Recursive Loop Printing The Last Value Twice At The End?
I am attempting to recursively loop through a number of files in a directory with subdirectories, looking for object attributes to match on. However, it seems that when I actually
Solution 1:
There are two calls of recursiveLoop
:
- The "main" one:
recursiveLoop(data, 'new');
- The "recursive" one:
recursiveLoop(value, name);
(which is called only one time as you can see from your log output)
As there are two calls and there is only one way to return from the function, console.log(6);
is called two times.
Solution 2:
Define recursiveLoop(data, name, depth)
(you will need a third parameter), call it as
x = recursiveLoop(data, 'new', 0);
at first, then always increase it, by calling
recursiveLoop(value, name, depth + 1);
and you will always know whether it is the first call or not. Then change your line which runs twice to
if (!depth) console.log(6);
so it will run only at the very first time. Your other mistake is that you add value.name
as a string to your array, not as a value, so change this line
myArr.push('value.name');
to
myArr.push(value.name);
Post a Comment for "Why Is My Recursive Loop Printing The Last Value Twice At The End?"