简体   繁体   English

如何使用字符串来引用变量?

[英]How can i use a string to reference a variable?

I have an array of strings: 我有一个字符串数组:

arr = ["bar","baz"]

and I have a few variables: 我有几个变量:

var bar = 'Hello';
var baz = 'bye';

using the array, how can I ouput: 使用数组,我如何输出:

hello
bye

I know how to loop, but, how can i use a string to refence a variable? 我知道如何循环,但是,如何使用字符串来引用变量?

The best option is to store the variables as properties within an object, and reference them that way: 最好的选择是将变量存储为对象内的属性,并以这种方式引用它们:

var data = {
    bar: "Hello",
    baz: "Bye"
};

arr.forEach((key) => doStuff(data[key]));

Failing that, if you have access to some other scope (perhaps this during a method call), you can keep the variable as properties on the scope. 如果做不到这一点,如果你有机会到其他范围(也许this方法调用时),你可以保持变量的作用域属性。

If you don't have any other scope available and no good options, all global variables are attached to the self (or window , when available) scope, so you can use the same sort of window[key] access. 如果没有其他可用范围,并且没有好的选择,则所有全局变量都将附加到self (或window ,如果可用)范围,因此可以使用相同的window[key]访问。

If the variables are global, you can access them by name using the property index of the window element: 如果变量是全局变量,则可以使用window元素的属性索引按名称访问它们:

 arr = ["bar","baz"] var bar = 'Hello'; var baz = 'bye'; arr.forEach(function(item) { alert(window[item]); }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM