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);

 

转载于:https://www.cnblogs.com/yicheng20110203/p/3540461.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值