Convert String to Variable Name in JavaScript

Convert string to variable name in JavaScript

If it's a global variable then window[variableName]
or in your case window["onlyVideo"] should do the trick.

Variable name as a string in Javascript

Typically, you would use a hash table for a situation where you want to map a name to some value, and be able to retrieve both.

var obj = { myFirstName: 'John' };

obj.foo = 'Another name';

for(key in obj)

console.log(key + ': ' + obj[key]);

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>

JavaScript convert a string to a variable name?

The eval way:

Not sure what are you doing and I hope you're aware of the bad sides of eval, but that's the only way you can turn this code into a working code:

var metFital = { "IMP_TRAV_SP": { type: "cont", Est: 0.055 }}

var IMP_TRAV_SP= 20;

var EvalueFital=0

for (var par in metFital) {

if (metFital[par].type == "cont") {

EvalueFital = EvalueFital + ((metFital[par].Est) * eval(par));

}

};

alert(EvalueFital);

Convert string to variable name to use in jQuery .animate

you can use window object to access global variables

var nextVar = window['nav'+nextLoc];

How to use a string as a variable name in Javascript?

Stop. Reorganise your code. If you want to select variables with a variable, then there has to be a logical grouping for them. Make it explicit.

var chat = {
"1": "one",
"2": "two"
};
var id = 1;
var new_is_a_keyword_and_cant_be_an_identifier = chat[id];


Related Topics



Leave a reply



Submit