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'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...

share|improve this question

closed as unclear what you're asking by Mike Brant, Paul, Shanimal, Chuck, Abbas May 1 at 23:47

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question.If this question can be reworded to fit the rules in the help center, please edit the question.

1  
So you want help, but don't want to explain what help you need? –  Mike Brant May 1 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) –  LJ_1102 May 1 at 22:57
    
possible duplicate of Javascript Global Variables –  Paul May 1 at 22:58
    
possible duplicate of "Variable" Variables in Javascript? –  Chuck May 1 at 23:13

1 Answer 1

up vote 1 down vote accepted

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.

share|improve this answer
    
Thank you so much, This fixed the problem! LOVE U –  user3594453 May 1 at 23:21

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