Get an array of all objects in a Javascript file
I was playing around with some Javascript code when I came across a question: Is there a way to find the quantity objects
in any javascript file and print it out to functions?
I haven't found anything on the internet that offers an answer to this question and I doubt it's possible, but if anyone has an idea I'd be interested to see it.
Sample code if it doesn't make sense:
var str = "Hello World!";
var num = 3.14;
var obj = {};
function printOutObjects() {
var objs = [];
// Find objects in script...
console.log(objs);
}
source to share
Well, ultimately, everything is part of the object window
, as a theoretical exercise you can use the following, but it will give you a little more than you bargained for (and might crash your computer):
var str = "Hello World!";
var num = 3.14;
var obj = {};
function printOutObjects() {
var objs = [];
objs.push(window);
recurseObj(window, objs);
console.log(objs);
}
function recurseObj(o, objs) {
if(typeof(o) == "undefined" || o == null || typeof(o) == "string" || typeof(o) == "number") {
return;
}
for(var c in o) {
// handle security exceptions and whatever else may come up
try {
// stop computer crashing
if(objs.length > 300) {
return;
}
else {
var obj = o[c];
// Ensure its not already in the results
if(objs.indexOf(obj) == -1) {
objs.push(obj);
recurseObj(obj, objs);
}
}
} catch(e){}
}
}
printOutObjects();
Tho I'm not sure why you would want to do this at all and you could just log window
in to the console and deploy if you want to see what's on your page.
source to share