欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScrip實(shí)現(xiàn)PHP print_r的數(shù)功能(三種方法)

 更新時(shí)間:2013年11月12日 15:43:41   作者:  
PHP print_r的函數(shù)很好用,可以用來打印數(shù)組、對(duì)象等的結(jié)構(gòu)與數(shù)據(jù),可惜JavaScript并沒有原生提供類似的函數(shù)。不過我們可以試著自己來實(shí)現(xiàn)這個(gè)函數(shù),下面提供一些方法與思路
方法一
復(fù)制代碼 代碼如下:

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+'] => ' + typeof(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;
}

方法二
復(fù)制代碼 代碼如下:

$(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(4*(depth+1)+1).join(' ');
    var indentNextTwo = new Array(4*(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':
   default:
     for(var key in o) {
    tmp += indentNextTwo + '[' + key + '] = ';
    tmp += print_r(o[key], (depth+1));
     }
    }
    result += type + "\n";
    result += indentNext + '(' + "\n";
    result += tmp;
    result += indentNext + ')' + "\n";
    return result;
  };
  alert(print_r(json));
   }(json));
 });
});

方法三
復(fù)制代碼 代碼如下:

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);
}

相關(guān)文章

最新評(píng)論