Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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
like image 996
John Avatar asked Jul 01 '10 09:07

John


People also ask

Can we create dynamic variable in JavaScript?

The simplest JavaScript method to create the dynamic variables is to create an array. In JavaScript, we can define the dynamic array without defining its length and use it as Map. We can map the value with the key using an array and also access the value using a key.

What is Dynamic JavaScript?

Dynamically-typed languages are those (like JavaScript) where the interpreter assigns variables a type at runtime based on the variable's value at the time.


2 Answers

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.

like image 96
David Hedlund Avatar answered Oct 13 '22 00:10

David Hedlund


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.

like image 43
Amr Elgarhy Avatar answered Oct 12 '22 23:10

Amr Elgarhy