Tuesday, December 6, 2016

Javascript获取对象的属性名及对应的属性值

for(attribute in obj){
     alert(attribute);
     //alert(obj[attribute]);
}

@reference_0
---------------------------------
The following function traverse an Object and output its content:
function outputObj(o) {
    var txt = "",
        depth = 0;
    var sp = function(n) {
        var s = "";
        for (var i = 0; i < n; i++) {
            s += "&nbsp&nbsp&nbsp&nbsp&nbsp.";
        }
        return s;
    };
    var sub = function(obj) {
        var attr;
        for (attr in obj) {
            if ((typeof obj[attr]) !== "object") {
                txt += sp(depth) + "[attr:" + attr + " - depth:" + depth + " - value:<b>" +
                           obj[attr] + "</b>]<br>";
            } else {
                txt += sp(depth) + "[attr:" + attr + " - depth:" + depth + "]...<br>";
                depth++;
                arguments.callee(obj[attr]);
            }
        }
        depth--;
        return txt;
    };
    return sub(o);
}
..........................................
$("#demo").html(outputObj(obj));

No comments:

Post a Comment