4

说我有一个功能:

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

谢谢!

4

2 回答 2

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 名称而不是值,那么您不需要内联报告。

于 2013-09-04T13:02:05.613 回答
0

参考

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;
}
于 2013-09-04T11:28:13.107 回答