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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With