javascript打印对象

由于没有现成的js打印对象方法,在此写了一个js类common

function common(){
this.counter_start = 1;
this.str = ‘<pre>‘;

this.is_array_obj = function($_arr_obj){
if(this.toString.apply($_arr_obj) === ‘[object Array]‘){
return true;
}
return false;
};

this.print_space_start = function(){
for(var i=1;i<=this.counter_start;i++){
this.str+=‘\t‘;
}
};

this.print_space_end = function(){
for(var j=1;j<=this.counter_start-1;j++){
this.str+=‘\t‘;
}
};

this.init_data = function(){
this.str = ‘<pre>‘;
this.counter_start = 1;
};

this.print_r_action = function($obj){
if(this.is_array_obj($obj)){
this.str+= ‘[array] => Array(‘;
}else if( (typeof $obj === ‘object‘) && (this.toString.apply($obj) !== ‘[object Array]‘) ){
this.str+= ‘[object] => Object{‘;
}else{
this.str+=‘[‘+(typeof $obj)+‘] => ‘+$obj;
}
this.str+= ‘<br/>‘;
if(typeof $obj === ‘object‘){
if($obj === null || $obj === undefined ){
this.print_space_start();
this.str+=$obj === null ? ‘[null] => null‘ : ‘[undefined] => ‘;
this.str+=‘<br/>‘;
this.print_space_end();
}
for(var $v in $obj){
this.print_space_start();
if((typeof $obj[$v] === ‘object‘) && !(this.is_array_obj($obj[$v])) ){
this.counter_start++;
this.print_r_action($obj[$v]);
this.counter_start--;
}else if(this.is_array_obj($obj[$v])){
this.counter_start++;
this.print_r_action($obj[$v]);
this.counter_start--;
}else{
this.str+=‘[‘+$v+‘] => ‘+(typeof $obj[$v])+‘(‘+$obj[$v]+‘)‘;
}
this.str+=‘<br/>‘;
}
this.print_space_end();
if(this.is_array_obj($obj)){
this.str+=‘)‘;
}else if( (typeof $obj === ‘object‘) && (this.toString.apply($obj) !== ‘[object Array]‘) ){
this.str+=‘}‘;
}
}
};

this.print_r = function($obj){
this.init_data();
this.print_r_action($obj);
this.str+=‘</pre>‘;
document.write(this.str);
}
}

//以上是打印对象的类,下面是打印方法调用

function print_r($obj){
var $common = new common();
$common.print_r($obj);
}

//调用很简单,如

print_r($your_obj);

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。