简体   繁体   English

这是我的递归函数中的问题吗?

[英]Is this an issue in my recursive function?

I need to run through a stack of HTML Elements.我需要遍历一堆 HTML 元素。 But all my attempts to write a recursive function didn't work.但是我写递归函数的所有尝试都没有奏效。

In the snippet below I cannot return value from if statement and afterwards from a function itself.在下面的代码段中,我无法从if statement和之后的function本身return值。

I can console.log the information I need, it gets there, but trying to return it, it doesn't work.我可以console.log我需要的信息,它到达那里,但试图return它,它不起作用。

I never had such an issue with returning some data that's why I decided to display it here so as to let a fresh-eye to revise the code.我从来没有遇到过返回一些数据的问题,这就是为什么我决定在这里显示它以便让新人修改代码。

function findElementByDataValue(target: EventTarget, data: {key: string, value: string}){

    if (target.dataset[data.key] === data.value) {
      return target;
    };

    if (target.children.length > 0) {

      for (const child in target.children) {
        const element = target.children[child];

        // I tried to return "recursive" function here too. "Return" Abrupt execution (as it should)
        if (element.children && typeof element === 'object') {
          findElementByDataValue(element, data);
        }

      }

    }

}

if you have any ideas or noticed an issue with my recursive function, I would appreciate any help.如果您有任何想法或注意到我的递归函数有问题,我将不胜感激。

Using the return keyword like you are doing.像您一样使用return关键字。

Your second function calls the first function without returning the value returned by the first function:您的第二个函数调用第一个函数而不返回第一个函数返回的值:

Replace代替

    if (element.children && typeof element === 'object') {
      findElementByDataValue(element, data);
    }

with:和:

    if (element.children && typeof element === 'object') {
      return findElementByDataValue(element, data);
    }

In general, run your code in a debugger (popular web browsers provide debuggers) to see what is going on.通常,在调试器(流行的 Web 浏览器提供调试器)中运行您的代码以查看发生了什么。

See some debuggers documentation:请参阅一些调试器文档:

If you are new to JavaScript, I suggest looking into unit testing and test-driven development .如果您不熟悉 JavaScript,我建议您研究单元测试测试驱动开发

Writing tests (early) will help you think of what can go wrong with your code and write more robust functions.编写测试(早期)将帮助您思考代码可能出现的问题并编写更健壮的函数。 Jasmine is nice, this article suggests many other JavaScript unit testing options Jasmine很好,这篇文章推荐了许多其他JavaScript 单元测试选项

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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