为什么我的递归循环在最后一次打印最后一个值两次? [英] Why is my recursive loop printing the last value twice at the end?

查看:56
本文介绍了为什么我的递归循环在最后一次打印最后一个值两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图递归地遍历带有子目录的目录中的许多文件,寻找匹配的对象属性.

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 :-(

我的目标是拥有一个数组: ['new']

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

这是一个 stackblitz ,其中

推荐答案

有两个 recursiveLoop 调用:

  1. 主要"对象: recursiveLoop(data,'new');
  2. 递归"代码: recursiveLoop(value,name); (从日志输出中只能看到一次)
  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)

由于有两次调用,只有一种方法可以从该函数返回,因此 console.log(6); 被调用了两次.

As there are two calls and there is only one way to return from the function, console.log(6); is called two times.

这篇关于为什么我的递归循环在最后一次打印最后一个值两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆