打印js对象
输出JavaScript对象的内部结构常常做调试用.
一个输出所有对象属性的例子如下:
Javascript代码
functiondump_obj(myObject){
vars="";
for(varpropertyinmyObject){
s=s+"\n"+property+":"+myObject[property];
}
alert(s);
}
以上代码有些简陋,看个完善些的
Javascript代码
<scriptlanguage="javascript">
varMAX_DUMP_DEPTH=10;
functiondumpObj(obj,name,indent,depth){
if(depth>MAX_DUMP_DEPTH){
returnindent+name+":<MaximumDepthReached>\n";
}
if(typeofobj=="object"){
varchild=null;
varoutput=indent+name+"\n";
indent+="\t";
for(variteminobj){
try{
child=obj[item];
}catch(e){
child="<UnabletoEvaluate>";
}
if(typeofchild=="object"){
output+=dumpObj(child,item,indent,depth+1);
}else{
output+=indent+item+":"+child+"\n";
}
}
returnoutput;
}else{
returnobj;
}
}
</script>
/**
*对象转json
*@param{Object}obj
*/
this.obj2Str=function(o){
if(o==undefined){
return"";
}
varr=[];
if(typeofo=="string")return"\""+o.replace(/([\"\\])/g,"\\$1").replace(/(\n)/g,"\\n").replace(/(\r)/g,"\\r").replace(/(\t)/g,"\\t")+"\"";
if(typeofo=="object"){
if(!o.sort){
for(variino)
//r.push("\""+i+"\":"+this.obj2Str(o[i]));
if(!!document.all&&!/^\n?function\s*toString\(\)\s*\{\n?\s*\[nativecode\]\n?\s*\}\n?\s*$/.test(o.toString)){
r.push("toString:"+o.toString.toString());
}
r="{"+r.join()+"}"
}else{
for(vari=0;i<o.length;i++)
//r.push(this.obj2Str(o[i]))
r="["+r.join()+"]";
}
returnr;
}
returno.toString().replace(/\"\:/g,'":""');
}
/**
*打印js的对象
*obj对象
*name名称
*indent缩减
*depth深度
*/
this.dumpObj=function(obj,name,indent,depth){
varMAX_DUMP_DEPTH=3;
if(depth>MAX_DUMP_DEPTH){
returnindent+name+":<MaximumDepthReached>\n";
}
if(typeofobj=="object"){
varchild=null;
varoutput=indent+name+"\n";
indent+="\t";
for(variteminobj){
try{
child=obj[item];
}catch(e){
child="<UnabletoEvaluate>";
}
if(typeofchild=="object"){
output+=this.dumpObj(child,item,indent,depth+1);
}else{
output+=indent+item+":"+child+"\n";
}
}
returnoutput;
}else{
returnobj;
}
}