1、有時候需要把對象中的字段屬性打印出來,下面用JS實現輸出對象:
1 function writeObj(obj) { 2 var description = ""; 3 for (var i in obj) { 4 var property = obj[i]; 5 description += i + " = " + property + "\n"; 6 } 7 alert(description); 8 }
2、結果對象是object而無法查看該對象里面的內容,用下面的函數,可以將其轉化為字符串類型,然后就可以打印出來了,具體代碼如下:
1 function obj2string(o){ 2 var r=[]; 3 if(typeof o=="string"){ 4 return "\""+o.replace(/([\'\"\\])/g,"\\$1").replace(/(\n)/g,"\\n").replace(/(\r)/g,"\\r").replace(/(\t)/g,"\\t")+"\""; 5 } 6 if(typeof o=="object"){ 7 if(!o.sort){ 8 for(var i in o){ 9 r.push(i+":"+obj2string(o[i])); 10 } 11 if(!!document.all&&!/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)){ 12 r.push("toString:"+o.toString.toString()); 13 } 14 r="{"+r.join()+"}"; 15 }else{ 16 for(var i=0;i<o.length;i++){ 17 r.push(obj2string(o[i])) 18 } 19 r="["+r.join()+"]"; 20 } 21 return r; 22 } 23 return o.toString(); 24 }
