Hello it is possible to access the value of a JavaScript variable by name? Example:
var MyVariable = \"Value of variable\";
function readValue(name) {
I tried the function below which was posted by Nicolas Gauthier via Stack Overflow to get a function from a string by naming it, and when used with the name of a variable, it returns the variable's value.
It copes with dotted variable names (values of an object). It works with global variables and variables declared with var, but NOT with variables defined with 'let' which are not visible in called functions.
/***
* getFunctionFromString - Get function from string
*
* works with or without scopes
*
* @param string string name of function
* @return function by that name if it exists
* @author by Nicolas Gauthier via Stack Overflow
***/
window.getFunctionFromString = function(string)
{
let scope = window; let x=parent;
let scopeSplit = string.split('.');
let i;
for (i = 0; i < scopeSplit.length - 1; i++)
{
scope = scope[scopeSplit[i]];
if (scope == undefined) return;
}
return scope[scopeSplit[scopeSplit.length - 1]];
}
var sen0=1;
if(window["sen"+n] > 0){
}
Yes, you can do it like this:
var MyVariable = "Value of variable";
alert(window["MyVariable"]);
Global variables are defined on the window
object, so you can use:
var MyVariable = "Value of variable";
alert(window["MyVariable"]);
var MyVariable = "Value of variable";
alert(readValue("MyVariable"));
// function readEValue(name) { readevalue -> readvalue // always do copy-paste to avoid errors
function readValue(name) {
return window[name]
}
That's all about ;o)
Try this ^_^
var MyVariable = "Value of variable";
alert(readValue("MyVariable"));
function readValue(name) {
return eval(name)
}