Categories: Js/AJAX | Tags: | Views: 813

 

做JavaScript开发, 特别是稍微复杂一点的程序, 难免要用到JavaScript面对对象的特性, 现在JavaScript的调试工具逐渐多和强大起来, 然而有时候要看一个object的值, 还是很不方便, 这时候就开始想念php的print_r功能了, 它可以将数组和对象的皮剥得干干净净, 让你看得一清二楚.

网上已经有很多版本了,但都不太好用,没有达到想要的效果,我自己写了一个, 稍微看得清楚一点.

先看一下效果图:

js_print_r

图中我只截取了一个元素,下面还有几个元素没有截取, 从这张图中可以看出来这个object的结构是:

[
   {  events: {
    unload: [ function(){...} ],
    load: [ function(){...} ]
   } },
  { … }
]

功能特色:

1. 同一父级下的子元素,不同的层级显示不同的字体颜色

2. 同一层级的开始和结束的地方用 | 连接, 极好辩认

3. 显示数据类型

4. 如果类型是函数的话, 格式保持不变( IE和firefox下表现不同, 但能保持格式 )

 源代码:

 

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
function print_r(o){
    function print(o,i){
        i = i || 0;  // how many tabs
        var color = '#'+('00000'+(Math.random()*0x1000000<<0).toString(16)).substr(-6); 
        // randomly generate a color
        var indent = '|    '
        // 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:' + color + '">' + name + " => "+ typeof(val) +'( </font>';
            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 style="color:' + color + '">' + ')</font>\n';
        }
        return ret;
    }
    if( typeof o == 'object' )
        return '<pre>'+print(o)+'</pre>';  //use pre to prevent structure destruction
    else
        return o;
}

 

这篇文章来自 迷途知返(PWWANG.COM), 转载请注明出处。 版权说明

  1. October 28th, 2009 at 11:10
    Reply | Quote | #1

    有点看不明白啊?

  2. fb
    March 30th, 2010 at 06:35
    Reply | Quote | #2

    xiexie le

;) :| :x :twisted: :roll: :oops: :o :mrgreen: :lol: :idea: :evil: :cry: :arrow: :P :D :?: :? :) :( :!: 8O 8)

你可以使用@somebody:开头, 来邮件通知somebody你回复了他的留言(用户名区分大小写).