JavaScript中是否有一种方法可以获取当前定义的所有局部变量的列表?

时间:2013-09-04 11:09:43

标签: javascript

说我有一个功能:

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

在JavaScript中是否有办法获取当前范围内所有变量的列表,因此list_of_all_local_variables将包含类似{a:12,b:13}的内容,甚至只包含['a','b']

谢谢!

2 个答案:

答案 0 :(得分:4)

非常快速攻击AST解决方案。

(这是我第一次玩Esprima,所以要温柔!我绝对肯定这可以改进)

<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>

将打印到控制台:

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

如果您只想要var名称而不是值,那么您就不需要内联报告。

答案 1 :(得分:0)

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;
}