问题:我想通过字符串访问我在js文件中获得的一些变量。
我知道,如果您有一个对象,可以选择接收变量值,并将对象关键字名称放在方括号中传递给该对象,但这不是这种情况。在这里,我只有一个公共变量,我希望通过向下发送一个字符串来获取其值。
我要实现的示例:
const constantName = 12345; // Value to access
const stringToUseToGetTheValueOfConstantName = 'constantName';
// I want to know how to get the '12345' by something like this:
const valueFinallyAccessed = `${stringToUseToGetTheValueOfConstantName}`; // I know this returns a string
console.log(valueFinallyAccessed); // 12345
解决方案
const valueFinallyAccessed = eval(stringToUseToGetTheValueOfConstantName);
console.log(valueFinallyAccessed); // Prints out the value 12345