如何仅使用字符串访问常量变量 [英] How Can I Access A Constant Variable With Only A String
问题描述
我有以下问题:
const value1 = "some value";
var value2 = "some value";
console.log(window["value1"]); // undefined
console.log(window["value2"]); // some value
我知道const是块作用域的,这就是我无法通过const访问它的原因窗口对象。我的问题是,有什么方法可以仅使用字符串标识符来访问const变量。
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.
如果我只能访问 value1,如何获取处理实际值1?
If all I have access to is "value1", how do I get a handle on the actual value1? Is it even possible?
推荐答案
看来,像let和const这样的块作用域声明没有添加到全局对象中,这意味着您无法通过window的属性访问它们。
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.
请参阅Stack Overflow上的以下相关问题:https://stackoverflow.com/a/28776236/10965456
See this related question on Stack Overflow: https://stackoverflow.com/a/28776236/10965456
eval应该可以工作 eval( values1)
,以及Function构造函数 new Function( return value1)()
,尽管我不确定为什么会这样必要。如果需要动态访问某些值,请改用数组,对象或映射。
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.
这篇关于如何仅使用字符串访问常量变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!