递归函数无法正常工作

时间:2016-01-21 02:12:58

标签: javascript jquery recursion

我有一个recusive函数,它应该循环遍历一个json对象并输出表达式。但是,我的注意力似乎已经消失了,因为它输出了 field1!='' AND field3 =='' 当它应该输出 field1!='' AND field2 =='' AND field3 ==''

我尝试过几个不同的东西,我能让它工作的唯一方法是创建一个全局变量outstring,而不是将其传递给函数。我在哪里?当我单步执行它时,我看到了正确的结果,但是一旦堆栈反转,它就会开始重置outstring,然后再次将其重新堆叠,但不会中间(field2)。

JSFiddle

function buildString(json, outstring) {
        var andor = json.condition;
    for (var rule in json.rules) {
        if (json.rules[rule].hasOwnProperty("condition")) {
            buildString(json.rules[rule], outstring);
        } else {
            var field = json.rules[rule].id;
            var operator = json.rules[rule].operator;
            var value = json.rules[rule].value == null ? '' : json.rules[rule].value;
            outstring += field + ' ' + operator + ' ' + value;
            if (rule < json.rules.length - 1) {
                outstring += ' ' + andor + ' ';
            }
        }
    }
    return outstring;
}

var jsonObj = {"condition":"AND","rules":[{"id":"field1","operator":"!= ''","value":null},{"condition":"AND","rules":[{"id":"field2","operator":"== ''","value":null}]},{"id":"field3","operator":"== ''","value":null}]};

$('#mydiv').text(buildString(jsonObj, ""));

2 个答案:

答案 0 :(得分:1)

该函数返回一个字符串。

当你从内部递归调用函数时,你没有对该实例返回的字符串做任何事情,只是调用无处可返回的函数

变化:

    if (json.rules[rule].hasOwnProperty("condition")) {
       buildString(json.rules[rule], outstring);
    } 

    if (json.rules[rule].hasOwnProperty("condition")) {
       // include the returned value in concatenated string
       outstring += buildString(json.rules[rule], outstring);
    }

DEMO

答案 1 :(得分:0)

为什么这么复杂?

function buildString(obj) {
    return "condition" in obj?
        obj.rules.map(buildString).join(" " + obj.condition + " "):
        obj.id + " " + obj.operator + " " + string(obj.value);
}

//this problem occurs quite often, write a utility-function.
function string(v){ return v == null? "": String(v) }