0

So I have been programming for a while, and have many times stumbled upon a chance to use randomly generated variable names which could be used later on. I was wondering if this sort of thing was possible with plain javascript without libraries and arrays, and how I would go about doing so.

An example of what I am thinking (To better show what I am trying to ask) -->

function makeVariables(max) {
    while(max < 10) {
 var c(max) = "test";   
 max++;
}
}

Now say it produced 10 variables named: c0, c1, c2, c3, c4, c5, c6, c7, c8, c9.

And then be able to call it later like...

alert(c4);

Even though I know these few lines of code don't work, I would like (If it is possible) an example of how I could get it to work.

EDIT

I have no problem with arrays, I was simply wondering if it was possible. I wish to make different variables that can be reached, but my question has been answered. So thanks for all you helpers!

  • 3
    What's wrong with an array? – Hauke P. Jun 26 '15 at 23:25
  • possible duplicate of [How do i declare and use dynamic variables in javascript?](http://stackoverflow.com/questions/5944749/how-do-i-declare-and-use-dynamic-variables-in-javascript) – CBroe Jun 26 '15 at 23:28
  • if you are looking for javascript to perform the same action as PHP then you are out of luck. What I mean is in PHP you can say the following: `$cool = 'test'` and then `$$cool = 5`. After which the variable $test will equal 5. As others have mentioned, you can use eval, or a window accessor to do what you want, but it's a bit of a hack. – tylerism Jun 26 '15 at 23:29
  • possible duplicate of ["Variable" variables in Javascript?](http://stackoverflow.com/questions/5187530/variable-variables-in-javascript) – Daedalus Jun 26 '15 at 23:30
  • 1
    In what sense is generating sequentially numbered names random? – nnnnnn Jun 27 '15 at 00:07

1 Answers1

2

How about something like:

function makeVariables(max, root) {
    // this would allow you to pass in a different 'container' for the vars
    root = root || window;
    while(max < 10) {
       root['c' + max] = 'test';
       max++;
    }
}

then you can do

makeVariables(10)
alert(c4);

which is the same as (variables are stored in the window object if you don't pass a 2nd param to the makeVariables function):

makeVariables(10)
alert(window['c4']);
Jaime
  • 6,736
  • 1
  • 26
  • 42
  • 2
    why do you have to have the root variable in the function? Could'nt you just do `window['c' + max]` instead of `root['c' + max]`? And couldn't you also do `alert(c4)` instead of `alert(window['c4'])? – markasoftware Jun 26 '15 at 23:36
  • 1
    Yes, I was just trying to make the point of where the variables are stored, I edited a bit so make it simpler, hopefully :) – Jaime Jun 29 '15 at 18:03