[英]Javascript - access the value of variables with dynamic name refereed
Noob question here :) Is there any way to access the value of a variable name refereed dynamically in javascript ? 这里的Noob问题:)有没有办法在javascript中访问动态引用的变量名的值?
What I tried : 我尝试了什么:
var var1 = "foo";
var var2 = "bar";
var i = 1;
i++;
console.log(`var${i}`); // give me "var2"
console.log(typeof `var${i}`); // == srting`
I want to access the value "foo" or "bar" but i'm missing something as I get only the name of the variable ? 我想访问值“foo”或“bar”,但我错过了一些东西,因为我只得到变量的名称?
My first question on stack, so if it's not perfect let me know I will add details, thank you ! 关于堆栈的第一个问题,如果它不完美,请告诉我我会添加细节,谢谢!
If your variables are defined in the global scope, they are properties of the window object. 如果变量是在全局范围内定义的,则它们是窗口对象的属性。
var var1 = "foo"; var var2 = "bar"; var i = 1; i++; console.log(window[`var${i}`]);
Probably a better approach is to create a data object and store variables as properties of that. 可能更好的方法是创建数据对象并将变量存储为其属性。
var data = {}; data.var1 = "foo"; data.var2 = "bar"; var i = 1; i++; console.log(data[`var${i}`]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.