Create Javascript Variable with name of a variable and string combined

…衆ロ難τιáo~ 提交于 2020-01-06 03:04:52

问题


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

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

num=1;

'vid'+num = 1;
// vid1=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: 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.


回答1:


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;


来源:https://stackoverflow.com/questions/14431432/create-javascript-variable-with-name-of-a-variable-and-string-combined

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