« Json object handling | Ads from different domains »
Real JS recursive dump!!!
By pavic | July 7, 2006
This can be a real pain in the ass. I was doing similiar stuff, but I can’t find it anymore. Thanks to guys from www….
Here is a code…
// return a string version of a thing, without name.
// calls recursive function to actually traverse content.
function dump(content) {
return dumpRecur(content,0,true) + "\n";
}
// put content into an alert box
function dumpAlert(label,content) {
alert(label+"\n"+dump(content));
}
function dumpConfirm(label,content) {
confirm(label+"\n"+dump(content));
}
// recursive function traverses content, returns string version of thing
// content: what to dump.
// indent: how far to indent.
// neednl: true if need newline, false if not
function dumpRecur(content,indent,neednl) {
var out = "";
if (typeof(content) == 'function') return 'function';
else if (dumpIsArray(content)) { // handle real arrays in brackets
if (neednl) out += "\n"+dumpSpaces(indent);
out+="[ ";
var inside = false;
for (var i=0; i
if (inside)
out+=",\n"+dumpSpaces(indent+1);
else
inside=true;
out+=dumpRecur(content[i],indent+1,false);
}
out+="\n"+dumpSpaces(indent)+"]";
} else if (dumpIsObject(content)) { // handle objects by association
if (neednl) out+="\n"+dumpSpaces(indent);
out+="{ ";
var inside = false;
for (var i in content) {
if (inside)
out+=",\n"+dumpSpaces(indent+1);
else
inside = true;
out+="'" + i + "':"
+ dumpRecur(content[i],indent+1,true);
}
out+="\n"+dumpSpaces(indent)+"}";
} else if (typeof(content) == 'string') {
out+="'" + content + "'";
} else {
out+=content;
}
return out;
}
// print n groups of two spaces for indent
function dumpSpaces (n) {
var out = '';
for (var i=0; i
return out;
}
// Naive way to tell an array from an object:
// it's an array if it has a defined length
function dumpIsArray (thing) {
if (typeof(thing) != 'object') return false;
if (typeof(thing.length) == 'undefined') return false;
return true;
}
// Naive way to tell an array from an object:
// it's an array if it has a defined length
function dumpIsObject (thing) {
if (typeof(thing) != 'object') return false;
if (typeof(thing.length) != 'undefined') return false;
return true;
}
//------------------------------------
Topics: PHP |
Comments are closed.

