javascript - javascript中的递归函数不返回标签

标签 javascript recursion

我正在尝试返回标签匹配项,但我似乎在这里做错了什么。有人可以把我推向正确的方向吗?

console.log('start');

var test = {
    "ID": 234324,
    "Label": "KDF",
    "children": [{
        "ID": 234234,
        "Label": "KJDF",
        "children": [{
            "ID": 234324,
            "Label": "KJDF"
        }, {
            "ID": 22323,
            "Label": "LKNDF"
        }, {
            "ID": 34535,
            "Label": "LKNSF"
        }]
    }, {
        "ID": 323434,
        "Label": "CLK"
    }]
}

function testThis(thing, ID) {
    if (thing.ID == ID) {
        console.log('match!')
        return thing.Label;
    } else if (thing.children && thing.children.length) {
        thing.children.forEach(function(x) {
            console.log(x);
            return testThis(x, ID);
        })
        return false;
    } else {
        return false;
    }



}




console.log(testThis(test, 323434));

console.log('end');

最佳答案

你在哪里

thing.children.forEach(function(x) {

使用.some()而不是 .forEach(),像这样

return thing.children.some(function(x) {})

.forEach() 返回未定义,而 .some() 将返回 truefalse 并且返回 true 后将停止迭代。

some() executes the callback function once for each element present in the array until it finds one where callback returns a true value. If such an element is found, some() immediately returns true. Otherwise, some() returns false.

fiddle : https://jsfiddle.net/mkarajohn/7ebr6pna/

关于javascript - javascript中的递归函数不返回标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36048912/

相关文章:

Javascript Web Worker - 如何忽略除最后一条消息之外的所有消息?

javascript - 将 var 分配给临时 var 不会阻止原始 var 发生变化

javascript - 运行 Node.js(在 Windows R2 服务器上): How can I reduce the amount of RAM that my grunt tasks consume?

javascript - 百分比倒计时

javascript - 是否可以使用爆米花 JS 导出带有视频叠加评论的视频?

ruby - 斐波那契数列递归的解释

python - 求解仅给定几个变量的简单方程组

C++ - 难以理解分而治之的功能

php - 类别树的递归 php mysql 查询/函数

algorithm - n 楼梯/台阶攀爬问题 : cannot conceptualize why T(n) = T(n-1) + T(n-2)