最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin4PV0评论

Say I have a function:

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

Is there a way in JavaScript to get a list of all the variables in the current scope, so list_of_all_local_variables would contain something like {a:12, b:13}, or even just ['a','b']

Thanks!

Say I have a function:

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

Is there a way in JavaScript to get a list of all the variables in the current scope, so list_of_all_local_variables would contain something like {a:12, b:13}, or even just ['a','b']

Thanks!

Share Improve this question asked Sep 4, 2013 at 11:09 superluminarysuperluminary 49.3k26 gold badges154 silver badges151 bronze badges 2
  • 1 Maybe this helps: stackoverflow./questions/2051678/… – Matt.C Commented Sep 4, 2013 at 11:10
  • Ah, looks like it's already been answered. I would have expected there to be a way to access the current scope, and the current scope chain in a dynamic language like JavaScript though. – superluminary Commented Sep 4, 2013 at 12:36
Add a ment  | 

2 Answers 2

Reset to default 4

A very quick stab at an AST solution.

(This is my first play with Esprima, so be gentle! I'm absolutely sure this can be 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) {
            for (var i = 0; i < body.length; i++) {
                _getvars(body[i]);
            }
        } else if ("VariableDeclaration" === body.type) {
            for (var i = 0; i < 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 a = 1, b = 2, ob = { name: "ob" };
    for (var i = 0; i < 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 to the 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 you only want the var names, and not the values, then you wouldn't need the inline reporting.

Reference

function getLocalVarNames (code)
{
    //Find variables declared as var, i.e. local variables in the given code
    var regex =/\bvar\b\s*(?:\s*(\w+)\s*(?:=[^,;]+)?)(?:\s*,\s*(\w+)\s*(?:=[^,;]+)?)*\s*;/g;
    var matches, result = [];
    while (matches = regex.exec(code))
    {
        for (var i = 1; i < matches.length; i++) {
            if (matches[i] != undefined) {
                //filter framework specific variables here
                if (matches[i] != "__ctx")
                    result.push(matches[i]);
            }
        }
    }
    return result;
}
Post a comment

comment list (0)

  1. No comments so far