无法在javascript中迭代对象

时间:2014-09-07 21:41:02

标签: javascript

努力在javascript中迭代对象。我通常可以进行明显的密钥迭代,甚至尝试了我为此目的找到的一些函数。虽然,当我将对象打印到控制台时,它可以工作。我正在努力访问其属性。困惑。这一次失去了相当长的一段时间,所以转向stackoverflow寻求帮助。

假设我将sitemap.xml存储在本地某处。

<script>

    (function() {

        tree = new TreeModel();

        root = tree.parse({ name: "domain.com" });

        var rootNode = root.first(function (node) {
            return node.model.name === "domain.com";
            });

        function idEq(name) {
            return function (node) {
             return node.model.name === name;
            };
         }

        var rootDomainHttp = "http://www.domain.com";
        var rootDomainHttps = "https://www.domain.com";
        var xmlhttp;
        if(window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        xmlhttp.onreadystatechange = function() {
            if(xmlhttp.readyState==4 && xmlhttp.status==200) {

                loc = xmlhttp.responseXML.documentElement.getElementsByTagName("loc");
                for(i=0;i<loc.length;i++) {

                    var fullURL = loc[i].firstChild.nodeValue;
                    //console.log(fullURL);
                    if(fullURL == rootDomainHttp || fullURL == rootDomainHttps)
                    {
                        document.getElementById("urls").appendChild(document.createTextNode( loc[i].firstChild.nodeValue ));
                        document.getElementById("urls").appendChild(document.createElement("br"));
                    }
                    else
                    {
                        fullURL = fullURL.replace(rootDomainHttps, '');
                        fullURL = fullURL.replace(rootDomainHttp, '');

                        var urlComponents = fullURL.split ('/').filter(function(el) {return el.length != 0});;
                        //console.log(urlComponents);
                        var arrayLength = urlComponents.length;
                        var currentNode;
                        var parentNode = root.first(idEq("domain.com"));
                        //console.log(fullURL);
                        for (var component in urlComponents) {
                            if (urlComponents.hasOwnProperty(component)) { 

                                //console.log("started loop for URL components: " + urlComponents[component]);

                                var currentNode = root.first(idEq(urlComponents[component]));

                                if (currentNode == undefined)
                                {

                                    parentNode.addChild(tree.parse({name: urlComponents[component]}));

                                    parentNode = root.first(idEq(urlComponents[component]));

                                }
                                else
                                {

                                    var currentNode = root.first(idEq(urlComponents[component]));


                                    var componentLevel = component;

                                    var nodesThatMatchPredicate = root.all(function (node) {
                                        return node.model.name == urlComponents[component];
                                    });
                                    var nodeLevel = 0;
                                    for(var node in nodesThatMatchPredicate)
                                    {
                                        if(nodeLevel != component)
                                        {

                                            parentNode.addChild(tree.parse({name: urlComponents[component]}));
                                        }
                                        else
                                        {
                                            //console.log("already exists...");
                                        }
                                    }   
                                    var parentNode = root.first(idEq(urlComponents[component]));
                                }
                             }
                        }                   
                        document.getElementById("urls").appendChild(document.createTextNode( loc[i].firstChild.nodeValue ));
                        document.getElementById("urls").appendChild(document.createElement("br"));

                    }
                }
            }       
        }
        xmlhttp.open("GET", "sitemap_001.xml", true);
        xmlhttp.send(null);
        console.log(JSON.stringify(root));
        console.log(JSON.stringify(root.model));

        //console.log(root);

        /*var url = 'data:text/json;charset=utf8,' + encodeURIComponent("something");
                        window.open(url, '_blank');
                        window.focus();*/

        })();

    </script>

I am using a <script type="text/javascript" src="http://jnuno.com/tree-model-js/vendor/jnuno/TreeModel.js"></script> library.

在控制台上,当我执行console.log(root)时;我明白了:  节点{config:Object,model:Object,children:Array [0],isRoot:function,hasChildren:function ...} children:Array [2] config:Objectmodel:Objectchildren:Array [2] 0:Objectchildren:Array [1] name:&#34; healthcarezone&#34; proto:Object1:Objectchildren:Array [1] name:&#34; protection&#34; proto:Objectlength:2__proto__:Array [0] name:&#34; domain.com&# 34; proto:Object__proto__:Node

但直接访问时。它给了我undefined。任何帮助和例子都非常赞赏。

1 个答案:

答案 0 :(得分:-1)

偶尔javascript不会按照您期望的顺序执行。 This article可能会对您有所帮助。

我认为一行代码花费的时间太长,无法返回后一行所依赖的变量的值。因此,当从不存在的变量运行计算时,您可以获得null和undefined值。您可能应该使用回调函数来确保在尝试使用所述变量之前返回变量。