问题
I have the following issue:
const value1 = "some value";
var value2 = "some value";
console.log(window["value1"]); // undefined
console.log(window["value2"]); // some value
I know that const is block scoped and that is the reason I cannot access it through the window object. My question is, is there any way to access a const variable using only a string identifier.
If all I have access to is "value1", how do I get a handle on the actual value1? Is it even possible?
回答1:
It appears that, block scope declarations, like let and const, are not added to the global object, meaning you can not access them through a property of window.
See this related question on Stack Overflow: https://stackoverflow.com/a/28776236/10965456
eval should work eval("values1"), as well as the Function constructor new Function("return value1")(), though I'm not sure why this is necessary. If you need to dynamically access certain values, use an array, object, or map instead.
来源:https://stackoverflow.com/questions/56926026/how-can-i-access-a-constant-variable-with-only-a-string