0

I’m looking to use arrays to create unique names for variables. I am not looking to store any calculated values in the arrays, but rather be able to declare variables using arrays to store the values. My attempts and research how to accomplish this leads me to think that it’s not even possible. I’d appreciate it if someone could let me know and if it is possible an answer/example on how to do it. I’ll post a simplified example on what I’m hoping to get working.

var indices = ["index01", "index02", "index03"];
var keys = ["key01", "key02", "key03"];
for (var index = 0; index < indices.length; index++)
{ 
    for (var key = 0; key < keys.length; key++)
    { 
        var  indices[index]+keys[key] //Looking for var index01key01, var index01key02 etc...
    }
}
Clay
  • 53
  • 1
  • 3
  • 11
  • Possible duplicate of [Convert string to variable name in Javascript](http://stackoverflow.com/questions/5613834/convert-string-to-variable-name-in-javascript). This gets asked frequently but I doubt it's a good idea. – Álvaro González Feb 05 '13 at 13:05
  • No, you must be doing something wrong ([XY-problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)). Why would you want to declare so many different variables? Use appropriate data structures instead. – Bergi Feb 05 '13 at 13:26

1 Answers1

0

Well, basic javascript variables are in the window scope, so try:

var indices = ["index01", "index02", "index03"];
var keys = ["key01", "key02", "key03"];
for (var index = 0; index < indices.length; index++)
{ 
    for (var key = 0; key < keys.length; key++)
    { 
        // you can now use the variable as window.index01key01, or just index01key01
        window[indices[index]+keys[key]] = null;
    }
}
Gareth Cornish
  • 4,357
  • 1
  • 19
  • 22
  • 1
    These variables are globally defined, but not locally. The OP has `var` keyword in the definition part. – VisioN Feb 05 '13 at 13:07
  • Thanks @Gareth and @Vision – works exactly. It's my Assembler coder that’s shining through. I'd actually read the other “Convert string to variable name in Javascript” posting but had failed to get it to work. But this makes me realize something. In the languages I mostly use (admittedly they are nearly all Mainframe sided) declarations are always required and they must always be explicit. As such in everything I’d tried I had begun with `var whatever`, if I hadn’t I would have found this solution a couple of days ago. It begs the question: is this a one-off are their many such cases. – Clay Feb 05 '13 at 15:30