0

I'm coding a game with CraftyJS which uses JavaScript and I ran into problem where I have for loop and I need to use Variable name based on Array String... I have been trying to make it work for few hours now so I'm too tired to explain but please help me if anyone hear this!

So basicly what I'm trying to do is this: var "TempVar"+Array[i] = Something;

also tried it whitout quotes etc... And by passing it in normal String and then using that but I didn't get it working either. If anyone know how this is supposed to do in JavaScript, or if there is alternative method please let me know that.

Sorry about my bad English, its terribly late and English is not my native language. Also notice that I'm new to JavaScript so don't hate me too hard...

4
  • 1
    So you want help, but don't want to explain what help you need? Commented May 1, 2014 at 22:54
  • 1
    Why exactly do you want to create a variable that is "dynamically" named ? I woudl really advice against doing so, but you could do so by using window["TempVar" + Array[i]] = Something; Also using global constructor names("Array") as variable names is not a good thing todo(in case you're doing so) Commented May 1, 2014 at 22:57
  • possible duplicate of Javascript Global Variables Commented May 1, 2014 at 22:58
  • possible duplicate of "Variable" Variables in Javascript? Commented May 1, 2014 at 23:13

1 Answer 1

1

Basically youre going to need to do this:

//Create an empty object
var myObject = {};

for(var i=0; i<Array.length;i++)
{
   //Add properties to the object
   myObject["TempVar"+Array[i]] = Something;
}

Create an empty object and then append new properties to it within your loop. JavaScript has this neat little way properties are accessed. You can either use a dot notation like so:

myObject.property = "Blah";

Or you could access the property like an array:

myObject["property"] = "Blah";

Both perform the same operation.

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.