How Can I Access A Constant Variable With Only A String

拥有回忆 提交于 2020-07-08 03:32:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!