如何从递归函数中断和返回

How to break and return from recursive functions?

本文关键字:返回 中断 递归函数      更新时间:2023-09-26

使用以下代码,该函数返回多次。我需要打破递归并只返回一次结果。

知道如何解决它吗?

http://jsfiddle.net/xhe6h8f0/

var data = {
    item: [{
        itemNested: [{
            itemNested2: [{
                id: "2"
            }]
        }]
    }]
};
function findById (obj, id) {
        var result;
        for (var p in obj) {
            if (obj.id) {
                if(obj.id == id) {
                    result = obj;
                    break; // PROBLEM HERE dos not break
                }
            } else {
                if (typeof obj[p] === 'object') {
                    findById(obj[p], id);
                }
            }
        }
        console.log(result);
        return result;
}
var result = findById(data, "2");
alert(result);

如果找到匹配项,则需要返回该值。在父调用中,如果递归调用返回一个值,那么它也必须返回该值。你可以像这样修改你的代码

function findById(obj, id) {
    var result;
    for (var p in obj) {
        /*
           if `id` is not in `obj`, then `obj.id` will evaluate to
           be `undefined`, which will not be equal to the `id`.
        */
        if (obj.id === id) {
            return obj;
        } else {
            if (typeof obj[p] === 'object') {
                result = findById(obj[p], id);
                if (result) {
                    return result;
                }
            }
        }
    }
    return result;
}

现在

var result = findById(data, "2");
console.log(result);

将打印

{ id: '2' }