gilbert-v
gilbert-v

Reputation: 1305

Get array of all objects in a Javascript file

I was playing around with some Javascript code, when I stumbled upon a question: Is there any way to find the amount of objects in any javascript file, and print them out of a function?
I haven't found anything on the internet which suggests an answer to this, and I doubt that this is possible, but if anyone has an idea, I would be interested to see it.

Code example if that didn't make sense:

var str = "Hello World!"; 
var num = 3.14; 
var obj = {};

function printOutObjects() { 
  var objs = [];
  // Find objects in script...
  console.log(objs);
}

Upvotes: 4

Views: 879

Answers (1)

Rhumborl
Rhumborl

Reputation: 16609

Well ultimately everything is part of the window object, so as a theoretical exercise you could use the following, but it will get you slightly more than you bargained for (and may 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 the console and drill down into it if you want to see what is in your page.

Upvotes: 1

Related Questions