Variable variables in JavaScript
tl;dr: Don't use eval
!
There is no single solution for this. It is possible to access some global variables dynamically via window
, but that doesn't work for variables local to a function. Global variables that do not become a property of window
are variables defined with let
and const
, and class
es.
There is almost always a better solution than using variable variables! Instead you should be looking at data structures and choose the right one for your problem.
If you have a fixed set of names, such as
// BAD - DON'T DO THIS!!!
var foo = 42;
var bar = 21;
var key = 'foo';
console.log(eval(key));
Use dynamic variable names in JavaScript
Since ECMA-/Javascript is all about Objects
and Contexts
(which, are also somekind of Object), every variable is stored in a such called Variable- (or in case of a Function, Activation Object).
So if you create variables like this:
var a = 1,
b = 2,
c = 3;
In the Global scope (= NO function context), you implicitly write those variables into the Global object (= window
in a browser).
Those can get accessed by using the "dot" or "bracket" notation:
var name = window.a;
or
var name = window['a'];
This only works for the global object in this particular instance, because the Variable Object of the Global Object is the window
object itself. Within the Context of a function, you don't have direct access to the Activation Object. For instance:
function foobar() {
this.a = 1;
this.b = 2;
var name = window['a']; // === undefined
console.log(name);
name = this['a']; // === 1
console.log(name);
}
new foobar();
Variable variables in JavaScript
var color = 'red';
window[color] = 'dark';
console.log(color, red);
Can I use a variable as variable name in JavaScript?
For just keeping an indicator/flag for a seen video, you could use Set
or if you need more stored information, take a Map
instead of using dynamically created variables where you still need to create an accessor for the variable as well.
var seen = new Set;
console.log(seen.has('foo')); // false;
seen.add('foo');
console.log(seen.has('foo')); // true;
JavaScript variable variables
Use brackets notation:
var o = new obj();
o.prop1 = "I'm the value";
var s = "prop1";
console.log(o[s]); // "I'm the value"
I think this is how this relates to your code:
["prop1","prop2","prop3"].forEach(function(prop) { // **A**
$("."+prop).unbind().blur(function(){
var id = $(this).siblings(".objID").html();
if(id >= 0)
{
objects[id][prop] = $(this).text()); // **B**
}
});
});
(B) is the place where we actually use the name, but note the (A) change to so that we get a value that won't change. You can't just use
// Wrong unless we also change the loop
objects[id][itemsIWantToBind[j]] = $(this).text());
because j
will be be beyond the end of the array when the event occurs.
forEach
is an ES5 feature that can readily be shimmed for old browsers. Or you can use jQuery's $.each
instead:
$.each(["prop1","prop2","prop3"], function(i, prop) { // **A**
$("."+prop).unbind().blur(function(){
var id = $(this).siblings(".objID").html();
if(id >= 0)
{
objects[id][prop] = $(this).text()); // **B**
}
});
});
Variable variables in JavaScript within a loop
You're trying to create variables with dynamic names so you could use window[variable_name]
.
NOTE: IMO you could use an array of values instead in this case.
var x = 1;var ctr = 5;
while (x <= ctr) { window["ss_" + x] = $('input[name=IDMenu_' + x + ']').val(); x++;}
console.log(ss_1, ss_2, ss_3, ss_4, ss_5);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="IDMenu_1" value="10"><input name="IDMenu_2" value="20"><input name="IDMenu_3" value="30"><input name="IDMenu_4" value="40"><input name="IDMenu_5" value="50">
How do I change the value of a global variable inside of a function
Just reference the variable inside the function; no magic, just use it's name. If it's been created globally, then you'll be updating the global variable.
You can override this behaviour by declaring it locally using var
, but if you don't use var
, then a variable name used in a function will be global if that variable has been declared globally.
That's why it's considered best practice to always declare your variables explicitly with var
. Because if you forget it, you can start messing with globals by accident. It's an easy mistake to make. But in your case, this turn around and becomes an easy answer to your question.
Set string to variable name
You can store the data in an object with the keys matching your select's values.
var data = {
basketball: "changeable-string",
handball: 760,
football: null,
baseball: "description: ball-game to play"
}
function myFunction(el) {
console.log(data[el.value])
}
<select name="box" onchange="myFunction(this);">
<option value="football">Football</option>
<option value="handball">Handball</option>
<option value="basketball">Basketball</option>
<option value="baseball">Baseball</option>
</select>
Related Topics
Onclick Open Window and Specific Size
Jquery Ui Accordion That Keeps Multiple Sections Open
Why Is ≪Marquee≫ Deprecated and What Is the Best Alternative
Dynamically Creating HTML Elements Using JavaScript
Document.Write() Overwriting the Document
How to Write in File (User Directory) Using JavaScript
JavaScript Data Grid For Millions of Rows
Drag Drop Files into Standard HTML File Input
Play an Audio File Using Jquery When a Button Is Clicked
How to Re-Trigger a Webkit CSS Animation Via JavaScript
Get Local Href Value from Anchor (A) Tag
Html 5 Video or Audio Playlist
How to Detect "Shift+Enter" and Generate a New Line in Textarea
How to Return the Response from an Asynchronous Call
How to Escape Quotes in HTML Attribute Values
Access CSS Variable from JavaScript
How to Merge Properties of Two JavaScript Objects Dynamically