John
John

Reputation: 101

Javascript/HTML, is it possible to create variable names from a loop

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

Upvotes: 10

Views: 8466

Answers (4)

Amr Elgarhy
Amr Elgarhy

Reputation: 69032

You can do something like this:

for(var i = 0; i<100; i++)
{
   eval("var beginning"+i);
}

For developers afraid from eval This is one of good articles talking about eval and how it is not an evil: http://www.nczonline.net/blog/2013/06/25/eval-isnt-evil-just-misunderstood/

I’m not saying you should go run out and start using eval() everywhere. In fact, there are very few good use cases for running eval() at all. There are definitely concerns with code clarity, debugability, and certainly performance that should not be overlooked. But you shouldn’t be afraid to use it when you have a case where eval() makes sense. Try not using it first, but don’t let anyone scare you into thinking your code is more fragile or less secure when eval() is used appropriately.

Upvotes: 5

pencilCake
pencilCake

Reputation: 53313

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.

Upvotes: 3

Shamanu4
Shamanu4

Reputation: 5406

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

Upvotes: 3

David Hedlund
David Hedlund

Reputation: 129832

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.

Upvotes: 7

Related Questions