1

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.

6
  • 8
    why not use array? Commented Jan 21, 2013 at 1:44
  • possible duplicate of Javascript - variable value is name of another variable Commented Jan 21, 2013 at 1:50
  • possible duplicate of Javascript Variable Variables Commented Jan 21, 2013 at 1:55
  • @JonathandeM. sorry, i want to stick to my code Commented Jan 21, 2013 at 1:58
  • @epascarello nope, mines simpler Commented Jan 21, 2013 at 1:59

1 Answer 1

5

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;
Sign up to request clarification or add additional context in comments.

4 Comments

And where is the eval option?
@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.
I just think that for the sake of completeness, it should be mentioned (and warned against of course).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.