模仿console自写函数打印js的对象

时间:2023-03-10 00:43:36
模仿console自写函数打印js的对象

本以为写个递归函数就可以将js的对象打印出来。

当然第一个想到的估计是JSON.stringify() 这个函数。但这个函数打印到浏览器 显示效果不友好。最友好的显示肯定是 控制台打印咯。

结果尝试打印window的时候,直接挂逼。原因就是对象循环引用。

经过几次修改,还是禁止了window里的某几个属性。

 function parseObjToString(obj){
var filter = ['top', 'window', 'document', 'localStorage', 'sessionStorage', 'cookie'], //不会解析该属性。
x = null, //没用的临时变量
n = '\n<br/>', //换行
Parse = {
parse_obj : function(obj, blank, parse_obj_times){//解析对象和数组
!parse_obj_times && (parse_obj_times = 0);
if (parse_obj_times > 20) {return '';}
switch(typeof obj){
case 'object':
var temp = '{',
isobj = true;
temp += n;
blank = blank || 1;
''+{}.toString.call(obj) === "[object Array]" && (isobj = false);
isobj ? temp = '{'+ n : temp = '['+ n;
for (x in obj) {
if (typeof obj[x] == 'object') {
if(filter.indexOf(x) !== -1 ) continue;
parse_obj_times ++;
temp += this.get_blank(blank)+ x+ ' : '+ this.parse_obj(obj[x], blank+1, parse_obj_times)+ ',' + n;
}else{
temp += this.get_blank(blank)+ x+ ' : '+ this.parse_sign(obj[x]) +',' + n;
}
}
temp = temp.substr(0, temp.length - (',' + n).length)+ n;
return temp + this.get_blank(blank - 1) + (isobj ? '}' : ']') ;
default :
return obj;
}
},
parse_sign: function(str){//解析特殊符号
return (''+str).replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n|\n\r/g, '<br>')
.replace(/\t/g, '&nbsp;&nbsp;').replace(/\s\s/g, '&nbsp;');
},
get_blank : function(num){//返回相应num的空白
for (var i = 0, blank=''; i < num; i++) {
blank += '&nbsp;&nbsp;&nbsp;&nbsp;';
}
return blank;
}
};
return Parse.parse_obj(obj);
}

测试数据:

 var obj = {
test : {
a : 'hello',
b : 'world',
c : {
d : {
e: {
f: {
g: {
h : {
i : {
shit : 'yes shit'
}
}
}
}
}
}
}
},
arr : [
'what',
'a',
'abc',
'<aaa><bbb>',
'a<asdfsafd>'
],
func : function(e){
console.log('aaaa');
},
func2: function(e){
console.log('bbbb');
},
func3: function(e){
console.log('asdfs');
}
}; var str = parseObjToString(obj);;
document.write(str);

测试结果:

模仿console自写函数打印js的对象