简体   繁体   中英

Create Javascript Variable with name of a variable and string combined

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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