使用变量名和字符串组合创建 Javascript 变量

使用变量名和字符串组合创建 Javascript 变量

问题描述:

我似乎无法解决这个问题,这就是我所拥有的...

I cant seem to solve this problem, heres what I have...

vid1=0;
vid2=0;
vid3=0;

num=1;

'vid'+num = 1;
// vid1=1;

我想根据数字创建变量,所以如果数字是2,那么就以vid2的名字创建一个变量,并将其设置为1.

I want to create the variable based on the number, so if the number is 2, then make a variable by the name of vid2 and set it equal to 1.

PS:这是我第一次使用 stackoverflow,很抱歉,如果我在本网站的传统方面犯了任何错误 =) 提前致谢.

PS: This is my first time on stackoverflow, so sorry if I made any mistakes in terms of tradition on this website =) And thannks in advanced.

如果您在全局命名空间中,请使用:

If you're in the global namespace, use this:

window['vid' + num] = 1;

但这是一个非常好的数组用例:

but this is a really good use case for an array:

var numbers = [0, 0, 0];
var num = 1;

numbers[num] = 1;