日期:2014-05-16  浏览次数:20337 次

正在学习js,自己写了个alert出对象信息的函数
正在学习js,自己写了个alert出对象信息的函数,欢迎大家批评指正,谢谢。。。
以下是代码

       function printObj(obj){
            var objStr = "print log : \n ";
            objStr += "obj: ";
            var o = obj;
            function toObjSource(){
                objStr += "{";
                for(k in o){
                    if(typeof o[k] == "object"){
                        objStr += k + ": ";
                        o = o[k];
                        toObjSource();
                    }else{
                        objStr += k + ": " + o[k] + ", ";
                    }
                }
                objStr = objStr.substr(0, objStr.lastIndexOf(","))
                objStr += " }, ";
                o = obj;
                return objStr;
            }
            return toObjSource;
        }

这样调用:
var o = jQuery.extend(true,
         { name: "John", location: { city: "Boston" }, school: {major: "computer", class: {teacher : "john", student: "marrry"} } },        
         { last: "Resig", location: { state: "MA" }, sex: "male", name: "jack" }
    );
var c = printObj(o);
var t = c();
alert(t = t.substr(0, t.lastIndexOf(",")));

1 楼 asilan 2011-11-29  
大家有空定一下啊,希望大家提提建议啊。。。