用于for的js递归函数

时间:2014-08-21 20:20:06

标签: javascript

在for循环中有forqursive的调用函数,但在工作中出错了。因为我认为循环中的原因,但我不明白为什么。帮助别人!

<html>
<head>
    <meta charset="utf-8"> 
    <title>Test html with js tasks</title>
    <script type="text/javascript" src='./2.js'></script>
</head>
<body>
    <script type="text/javascript">
        var objSample = {
            "glossary": {
                "title": "example glossary",
                "GlossDiv": {
                    "title": "S",
                    "GlossList": {
                        "GlossEntry": {
                            "ID": "SGML",
                            "SortAs": "SGML",
                            "GlossTerm": "Standard Generalized Markup Language",
                            "Acronym": "SGML",
                            "Abbrev": "ISO 8879:1986",
                            "GlossDef": {
                                "para": "A meta-markup language, used to create markup languages such as DocBook.",
                                "GlossSeeAlso": ["GML", "XML"]
                            },
                            "GlossSee": "markup"
                        }
                    }
                }
            }
        };
        findProperty(objSample, 'SGML');
    </script>
    Pikabu
</body>
</html>

和2.js的源代码:

function findProperty(obj, propContentPart) {
    for (var key in obj) {
        var value = obj[key];
        if (typeof value === 'object') {
            if (findProperty(value, propContentPart)) {
                console.log(key);
                return true;
            }
        } else {
            if (value.indexOf(propContentPart) > -1){
                console.log(key);
                return true;
            }
        }
    }
}

输出是:

ID
GlossEntry
GlossList
GlossDiv
glossary

但预计还有SortAs和Acronym。为什么这样?

1 个答案:

答案 0 :(得分:0)

  1. 使用typeof时要小心,例如,使用typeof on array给出'object'。我更喜欢使用instanceof Object来检查请求者prop是否是一个对象。
  2. indexOf仅适用于数组,不适用于对象。为了给出预期的结果,“SortAs”:“SGML”和“缩写”:“SGML”应该是数组:“缩写”:[“SGML”]