Is there a way in JavaScript to get a list of all the local variables currently defined? -


say have function:

function() {   var = 12;   var b = 15;   var c = list_of_all_local_variables } 

is there way in javascript list of variables in current scope, list_of_all_local_variables contain {a:12, b:13}, or ['a','b']

thanks!

a very quick stab @ ast solution.

(this first play esprima, gentle! i'm absolutely sure can improved)

<style> pre {     font-size: 8pt;     font-family: lucida console, monospace; } </style>  <pre id="ast"></pre>  <script src="esprima.js"></script>  <script> function getvars(fnstr) {     function _getvars(body) {         if (!body) {             return;         }         if (body.length) {             (var = 0; < body.length; i++) {                 _getvars(body[i]);             }         } else if ("variabledeclaration" === body.type) {             (var = 0; < body.declarations.length; i++) {                 vars.push(body.declarations[i].id.name);             }         } else if (body.body) {             _getvars(body.body);         }     }     var vars = [];     var syntax = esprima.parse(fnstr);     _getvars(syntax.body);     document.getelementbyid("ast").innerhtml = json.stringify(syntax, null, 4);     return vars; }  function myfn() {     var = 1, b = 2, ob = { name: "ob" };     (var = 0; < 10; i++) {         var s = "" + i;     }     getvars(myfn.tostring()).foreach(function(___var) {         var ___ob = eval(___var);         console.log(___var, (typeof ___ob), eval(___ob));     }); }  myfn(); </script> 

will print console:

a number 1 local-vars-in-function.html:44 b number 2 local-vars-in-function.html:44 ob object object {name: "ob"} local-vars-in-function.html:44 s string 9 local-vars-in-function.html:44 

if want var names, , not values, wouldn't need inline reporting.


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -