开发者

JavaScript function, which reads connections between objects

I have a JavaScript literal:

var members = {
    "mother": {
        "name" : "Mary",
        "age" : "48",
        "connection": {
            "brother" : "sun"
        }
    },
    "father": {
        "name" : "Bill",
        "age" : "50"
    },
    "brother": {
        "name" : "Alex",
        "age" : "28"
    }
}

Than I have a function, which should read connections from the literal above. It looks like this:

开发者_StackOverflow社区
 function findRelations(members){
    var wires = new Array();
    var count = 0;
    for (n = 0; n < members.length; n++){
         alert(members.length); // this alert is undefined
        if (members[n].connection){
            for (i = 0; i < members[n].connection[0].length; i++){
                var mw = new Array();
                var destination = 0;
                for (m = 0; m < members.length; m ++){
                    if (members[m] == members[n].connection[0]){
                        destination = m;
                        mw = [n, destination];
                        wires [count] = mw;
                        count++;
                    }
                }
            }
        }
    }
    return wires;
 }

However, when I run this function, I get nothing. And the first alert, which is placed inside the function shows 'undefined' at all.

findRelations(members);
alert("Found " + wires.length + " connections");

I guess that's because of JavaScript literal. Could you suggest how to change a function or perhaps to change litteral to JSON array to get it work?! And at the end to get 'm' and 'n' values as numbers.


What is a 'literal'? I guess you mean 'an object created using the literal notation'.

Only Array's (and strings) have a length property, what you want is to loop through the properties

for (var prop in members) {
    if (members.hasOwnProperty(prop)) {
          alert("members has property " + prop);
    }
}

This should get you on the right path as its not easy to follow the rest of the logic


The alert gives you "undefined" because your function seems to be expecting an array whereas your "members" variable is an Object.

the "length" property is not defined on an object. So,

var a = {
    name:'test',
    age:56
};
console.log(a.length);  //undefined

The same is the reason for getting no response as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜