Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
8  
why not use array? –  Jonathan de M. Jan 21 at 1:44
 
possible duplicate of Javascript - variable value is name of another variable –  epascarello Jan 21 at 1:50
 
possible duplicate of Javascript Variable Variables –  Felix Kling Jan 21 at 1:55
 
@JonathandeM. sorry, i want to stick to my code –  royjr Jan 21 at 1:58
 
@epascarello nope, mines simpler –  royjr Jan 21 at 1:59
show 1 more comment

1 Answer

up vote 5 down vote accepted

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;
share|improve this answer
 
 
+1^8 (where 8 = infiniti) =) I love it! –  royjr Jan 21 at 2:02
 
And where is the eval option? –  RobG Jan 21 at 2:50
 
@RobG - I don't go down the sewer drain without full body anti-toxic protective clothing. You get me that, and I'll get you eval. –  Joseph Silber Jan 21 at 2:52
 
I just think that for the sake of completeness, it should be mentioned (and warned against of course). –  RobG Jan 22 at 8:58
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.