简体   繁体   中英

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 perform a recursive loop, I cannot get the desired outcome and it seems I am printing my last debug log twice for some reason.

Can somebody enlighten me on what is going wrong?

 data = { myFile: { new: { name: 'new' } } }

  recursiveLoop(data, name) {
      let myArr = ['one'];
      console.log(1);
      for (const value of Object.values(data)) {
          console.log(2);
          if (value.name) {
              console.log(3);
              if (value.name === name) {
                  console.log(4);
                  myArr.push('value.name');
              }
          } else {
              console.log(5);
              recursiveLoop(value, name);
          }
      }
      console.log(6);
      return myArr;
  };

  x = recursiveLoop(data, 'new');
  console.log(x);

The debugging console log reads:

1
2
5
1
2
3
4
6
6

The array printed at the end is empty...

I cannot figure out what is going wrong :-(

My goal is to have an array: ['new']

Here is a stackblitz with it in

There are two calls of recursiveLoop :

  1. The "main" one: recursiveLoop(data, 'new');
  2. 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.

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);

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