【问题标题】:Recursive search through and object in JavaScriptJavaScript中的递归搜索和对象
【发布时间】:2014-05-26 16:18:53
【问题描述】:

我正在尝试在对象中进行递归搜索,并且我正在尝试根据某些条件查找 所有 匹配项。我正在使用以下功能:

function checkForTitleMatch(query, node) {
    var results = [];

    if (node.attr.title.indexOf(query) != -1) {
        results.push = node;
    }

    for (var i = 0; i < node.children.length; i++) {
        checkForTitleMatch(query, node.children[i]);
    }            

    return results;
}

我不认为匹配有问题等等 - 我认为问题在于我在递归中返回结果的方式。

在我的情况下,结果始终是一个空数组,因为第一个/根元素永远不会匹配(在我的情况下),并且没有正确返回子迭代的结果,恕我直言。

请有人纠正我或指出为了得到正确的结果必须改变什么吗?

【问题讨论】:

  • 我想知道如果结果不是空数组,我不应该推动子递归,但必须有一种更清洁的方式:/

标签: javascript recursion


【解决方案1】:

你有两个问题:

(1)results.push = node;应该是results.push(node)

(2) 每次调用checkForTitleMatch 都会创建自己的results 数组,并且这些数组永远不会聚合。

解决此问题的一种可能方法:

function checkForTitleMatch(query, node) {
    var results = [];

    (function check(node) {
        if (node.attr.title.indexOf(query) != -1) {
            results.push(node);
        }

        for (var i = 0; i < node.children.length; i++) {
            check(node.children[i]);
        }
    })(node);           

    return results;
}

使用attribute selector 更清晰/更快,例如

node.querySelectorAll('*[title*=' + query + ']');

虽然这不会查询顶级节点node,并假设query 没有“特殊字符”。

【讨论】:

  • 天哪,我真的做了push = node吗? :D 星期一早上.. 非常感谢!我去看看!
  • 完美运行。谢谢!
【解决方案2】:

值得注意的是,您可以通过使用Array.concat 合并结果来解决此问题,而无需关闭:

function checkForTitleMatch(query, node){
    var results = [];

    if (node.attr.title.indexOf(query) != -1){
        results.push(node);
    }

    for (var i=0; i<node.children.length; i++){
        results = Array.prototype.concat.apply(results, 
            checkForTitleMatch(query, node.children[i])
        );
    }            

    return results;
}

另见:Function.prototype.apply()

【讨论】:

    猜你喜欢
    • 2014-04-08
    • 2011-10-02
    • 2016-05-05
    • 2019-02-03
    • 2022-10-14
    • 2023-04-04
    • 2017-03-02
    • 2022-01-11
    相关资源
    最近更新 更多