JavaScript对象查看器代码
// obj: object to inspect // dest: destination to put the results in. function inspect(obj, dest) { // prefent for errors if(obj == undefined || dest == undefined) return; if(window.jQuery) { obj = $(obj).get()[0]; dest = $(dest).get()[0]; } var keys = [], values = []; // functions var makeTableRow= function(val1, val2) { var tr = document.createElement("tr"), tdL = document.createElement("td"), tdR = document.createElement("td"); tr.appendChild(tdL); tr.appendChild(tdR); tdL.appendChild(document.createTextNode(val1)); tdR.appendChild(document.createTextNode(val2)); return tr; }; var setBooleanStyle = function(es) { es.color = "blue"; }; var setNumberStyle = function(es) { es.color = "darkblue"; es.fontWeight = "bold"; }; var setUndefinedStyle = function(es) { es.color = "black"; }; var setFunctionStyle = function(es) { es.color = "purple"; }; var setStringStyle = function(es) { es.color = "red"; es.fontStyle = "italic"; }; var setObjectStyle = function(es) { es.color = "green"; }; var setDefaultStyle = function(es) { // }; // filter own properties for (var key in obj) { if(obj.hasOwnProperty(key)) { keys.push(key); values.push(obj[key]); } } // render // table var table = document.createElement("table"), thead = document.createElement("thead"), tbody = document.createElement("tbody"); table.appendChild(thead); table.appendChild(tbody); // header thead.appendChild(makeTableRow("Key", "Value")); // body for(var i = 0; i<keys.length; i++) { var tr = document.createElement("tr"), left = document.createElement("td"), right = document.createElement("td"); left.appendChild(document.createTextNode(keys[i])); right.appendChild(document.createTextNode(values[i])); tbody.appendChild(tr); tr.appendChild(left); tr.appendChild(right); // style var ls = left.style; ls.color = "gray"; ls.fontWeight = "bold"; ls.fontFamily = "Courier New"; ls.fontSize = "12px"; var rs = right.style; rs.fontFamily = "Courier New"; rs.fontSize = "12px"; switch(typeof values[i]) { case "number": setNumberStyle(rs); break; case "undefined": setUndefinedStyle(rs); break; case "boolean": setBooleanStyle(rs); break; case "object": setObjectStyle(rs); break; case "string": setStringStyle(rs); break; case "function": setFunctionStyle(rs); break; default: setDefaultStyle(rs); } } dest.appendChild(table); }