简单的js调试函数

2010-10-20 01:57

简单的js调试函数

by joe

at 2010-10-19 17:57:38

original http://xiebiji.com/2010/10/%e7%ae%80%e5%8d%95%e7%9a%84js%e8%b0%83%e8%af%95%e5%87%bd%e6%95%b0/

有时候我们不得不把某个js的数组或者对象打印出来,就好像php的print_r一样,js没有这种函数,我在网上找了一个并且稍微改造了一下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
//js调试函数
function dump(o){
    tips=document.createElement("div");
    tips.className='dump_tips';
    tips.style.cssText="position:fixed;bottom:0;left:10px;height:400px;width:400px;overflow:auto;background:#000;border:1px solid #333;padding:10px";
    tips.innerHTML=(print_r(o));
    document.getElementsByTagName('BODY')[0].appendChild(tips);
    print_r(o);
    function print_r(o){
        function print(o,i){
            i = i || 0;  // how many tabs
            var color = '#0074ce'; 
            // randomly generate a color
            var indent = '<font style="color:#333">-----</font>'
            // form of a tab, you can use '|\t' instead
 
            var space = '';
            for( var k=0; k<i; k++ ){
                space += indent;
            }
            var ret = '';
            for( var name in o ){
                var val = o[name];   
                ret += space + '<font style="color:#96eff2">' + name + ' <font style="color:#6d6d6d">=></font> '+ '<font style="color:#666">' + typeof(val) +'</font>'+'</font>'+'<font style="color:#6d6d6d">( </font>';
                ret+='<font style="color:#96eff2">';
                if( typeof val == 'object' ){
                    ret += '\n'+print(val,i+1);
                    ret += space;
                } else if( typeof val == 'function' ){
                    ret += '\n' + space + indent + val.toString().replace(/\n/g, '\n'+space+indent)+'\n'+space;
                } else
                    ret += val + ' ' ;
                ret+='</font>';
                ret += '<font style="color:#6d6d6d">' + ')</font>\n';
            }
            return ret;
        }
        if( typeof o == 'object' )
            return '《pre》'+print(o)+'《/pre》';//把这里《》变成<>
        else
            return o;
    }
}
与本文相关的日志