PHP Print_r function is very easy to use, online casino can be used to print groups, objects, such as the structure and data, unfortunately, JavaScript does not provide a similar function of native. But we can try to implement this function on our own, here are some ideas and methods.
Method One
function Print_r (theobj) { var retstr = '; if (typeof theobj = = ' object ') { retstr + = ' <div style= "font-family:tahoma; font-size:7pt;" > '; For (var p in theobj) { if (typeof theobj[p] = = ' object ') { retstr + = ' <div><b>[' +p+ '] = = + Typeo F (theobj) + ' </b></div> '; Retstr + = ' <div style= "padding-left:25px; > ' + print_r (theobj[p]) + ' </div> '; } else { Retstr + = ' <div>[' +p+ '] = <b> ' + theobj[p] + ' </b></div> '; }} Retstr + = ' </div> '; } return RETSTR;}
Method Two
$ (document). Ready (function () {$ (' #btn '). Click (function () { var jsonstr = $ (' #jsonData '). Val (); var json = eval (' (' +jsonstr+ ') '); (function () {var print_r = function (o, depth) { var result = '; Depth | | (depth=1); var indent = new Array (4*depth+1). Join ('); var indentnext = new Array (depth+1) +1. Join ('); var indentnexttwo = new Array (depth+2) +1. Join ('); var tmp = '; var type = typeof O; Switch (type) {case ' string ': Case ' number ': Case ' Boolean ': Case ' undefined ': case ' function ': tmp + = indent + Indentnext + O + "\ n"; Break;case ' object ':d efault: for (var key in O) {tmp + = indentnexttwo + ' [' + key + '] = '; tmp + = Print_r (O[key], (DEP th+1)); } } Result + = type + "\ n"; Result + = Indentnext + ' (' + ' \ n '); result + = tmp; Result + = Indentnext + ') ' + ' \ n '; return result;}; Alert (Print_r (JSON)); } (JSON));});
Method Three
Print_r:function (theobj) {var retstr = '; if (typeof theobj = = ' object ' | | typeof theobj = = ' array ') {retstr + = ' <div style= "font-family:tahoma; font-size:7pt;" > '; for (var p in theobj) {if (typeof theobj[p] = = ' object ' | | typeof theobj[p] = = ' array ') {retstr + = ' <div><b >[' +p+ ' = + ' + typeof (Theobj) + ' </b></div> '; retstr + = ' <div style= ' padding-left:25px; " > ' + xfupload. Tools.print_r (Theobj[p]) + ' </div> ';} else {retstr + = ' <div>[' +p+ '] = <b> ' + theobj[p] + ' </b></div> ';}} Retstr + = ' </div> ';} $ ("Body"). Append (RETSTR);}
Write a PHP Print_r-like function with JavaScript