在PHP中,我们打印一个数组或者对象的时候,都是用print_r,相对比较直观,可是javascript就不行。翻了翻资料,也看到一些代码的写法。这里是一个简单的处理(不能打印window,document等对象):
JavaScript代码
- function print_r( $value ){
- if($value.constructor == Array || $value.constructor == Object ){
- document.write("<ul>");
- for (var $i in $value){
- if($value[$i].constructor == Array || $value[$i].constructor == Object ){
- document.write("<li>["+$i+"] => " + typeof( $value ) + " </li><ul>");
- print_r($value[$i]);
- document.write("</ul>");
- }else{
- document.write("<li>["+$i+"] => " + $value[$i] + "</li>");
- }
- }
- document.write("</ul>");
- }
- }
- var s = {};
- s.i = '123';
- s.o = {};
- s.o.test = 'tt';
- print_r(s);
然后看了一下phpjs.org,它上面的print_r就比较复杂了。。。
JavaScript代码
- function print_r (array, return_val) {
- // Prints out or returns information about the specified variable
- //
- // version: 1008.1718
- // discuss at: http://phpjs.org/functions/print_r // + original by: Michael White (http://getsprink.com)
- // + improved by: Ben Bryan
- // + input by: Brett Zamir (http://brett-zamir.me)
- // + improved by: Brett Zamir (http://brett-zamir.me)
- // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // - depends on: echo
- // * example 1: print_r(1, true);
- // * returns 1: 1
- var output = "", pad_char = " ", pad_val = 4, d = this.window.document; var getFuncName = function (fn) {
- var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
- if (!name) {
- return '(Anonymous)';
- } return name[1];
- };
- var repeat_char = function (len, pad_char) {
- var str = ""; for (var i=0; i < len; i++) {
- str += pad_char;
- }
- return str;
- };
- var formatArray = function (obj, cur_depth, pad_val, pad_char) {
- if (cur_depth > 0) {
- cur_depth++;
- }
- var base_pad = repeat_char(pad_val*cur_depth, pad_char);
- var thick_pad = repeat_char(pad_val*(cur_depth+1), pad_char);
- var str = "";
- if (typeof obj === 'object' && obj !== null && obj.constructor && getFuncName(obj.constructor) !== 'PHPJS_Resource') {
- str += "Array\n" + base_pad + "(\n";
- for (var key in obj) {
- if (obj[key] instanceof Array) {
- str += thick_pad + "["+key+"] => "+formatArray(obj[key], cur_depth+1, pad_val, pad_char); } else {
- str += thick_pad + "["+key+"] => " + obj[key] + "\n";
- }
- }
- str += base_pad + ")\n"; } else if (obj === null || obj === undefined) {
- str = '';
- } else { // for our "resource" class
- str = obj.toString();
- }
- return str;
- };
- output = formatArray(array, 0, pad_val, pad_char);
- if (return_val !== true) {
- if (d.body) {
- this.echo(output);
- } else {
- try {
- d = XULDocument; // We're in XUL, so appending as plain text won't work; trigger an error out of XUL
- this.echo('<pre xmlns="http://www.w3.org/1999/xhtml" style="white-space:pre;">'+output+'</pre>');
- } catch (e) {
- this.echo(output); // Outputting as plain text may work in some plain XML
- }
- }
- return true; } else {
- return output;
- }
- }
果然是没有做不到的事,只有想不到的事呀。。。(上面的phpjs.org的print_r需要echo方法,请到phpjs.org下载)