tags:

views:

52

answers:

4

Imagine i had: <div id names>142,140,150</names>

could i then (in Javascript) write a forloop which declares variable names, with these values appended ie

var list = document.getElementById('names').innerHTML.Split(',');

for(i=0; i<list.Length; i++){
    var 'beginning' + list[i];
}

so i'd essentially want to create:

var beginning142
var beginning140
var beginning150
+3  A: 

You can indeed:

window['beginning' + list[i]] = 'value';

Funny coincidence, I answered a very closely related question 10 seconds prior to this one, and then I used exactly this as an example. So a more elaborate explanation on why this works is available here.

David Hedlund
+1 for good answer. Javascript handles obj.test the same way as obj["test"], and since all variables that are global is stored in the window-object you can do window["test"] = "something"; alert(test); and get an alert-box stating "something".
Alxandr
+2  A: 

I can't add comment to your question due to low reputation score - this is not answer but advice. I think It would be better to create single array with your keys 142,140,150...

Shamanu4
His question was wheater or not this was possible, not if it's recomanded.
Alxandr
Nonetheless. A word of warning is required, as ‘variable variables’ are almost always a dreadful mistake. Most people asking here how to use them are Doing It Wrong in a major way.
bobince
A: 

You can do something like this:

for(var i = 0; i<100; i++)
{
   eval("var beginning"+i);
}
Amr ElGarhy
+1  A: 

Why don't you define an object that has those values as an attribute on it.

For example:

var myVariable = function(id, value){
 this.Id = id;
 this.Value = value;
};

then you can just instantiate this object. I think it is less complicated and more readable in the end.

burak ozdogan
+1 - with the flexibility of JavaScript objects aka `{}`, it's easy to forget that creating new types of objects is equally easy.
Anurag