从一串声明中检索变量的值

时间:2018-02-17 12:12:06

标签: javascript node.js

我有以下名为 abc 字符串(由javascript变量声明组成):

var abc = `
    var exp = 'test';
    var test = 15;
    var test2 = "wow";
`;

我希望从此字符串中获取exptesttest2的值。

可能有效的方法之一是:

eval(abc);

然而,出于安全目的,此解决方案不适用于打字稿,您会推荐其他方法(随意提出一些npm库)?

2 个答案:

答案 0 :(得分:0)

创建函数并传递变量。

  与函数new Function相比,

eval具有封闭的范围。

var abc = `
    var exp = 'test';
    var test = 15;
    var test2 = "wow";
`;

var fn = (variable) => (new Function('', `${abc} return ${variable};`))();

console.log(fn('exp'));
console.log(fn('test'));
console.log(fn('test2'));

答案 1 :(得分:0)

这样做的一种方法如下: 首先,我们通过使用;作为分隔符

来分割字符串来查找声明

现在我们找到声明之后,我们使用map()来提取每个声明的值并将其返回到一个新数组中。要找到声明的值,我们使用'='将其分成两部分。第一部分是声明名称,第二部分是声明值

var abc = `var exp = 'test';
    var test = 15;
    var test2 = "wow";`;
//Trim string
abc = abc.trim();
//Split by ';'
var declarations = abc.split(';');
//The last item is empty so we remove it
declarations.pop();
console.log(declarations)
//Now that we have the declarations we need to get the values
//so we split each declaration using '='
var values = declarations.map(function(dec){
  var value = dec.split("=").pop()
  return value;
  
});


//Bonus
//This gets all declarations from a string and returns them as a key value object
function getDeclarations(s) {
    
    var variables = s.split(";");
    //Last variable is an empty string so pop it
    variables.pop()
    var declarations = {};
    variables.forEach(function (variable) {
        variable = variable.trim()
        var name = variable.split("=")[0].split("var")[1];
        var value = variable.split("=").pop();
        name = name.trim();
        value = value.trim();
        declarations[name] = value;
    });
    return declarations;
}
console.log(values)

console.log(getDeclarations(abc))