Get Global Variable Dynamically by Name String in JavaScript

Get global variable dynamically by name string in JavaScript

Do you want to do something like this?

<script>
//in one script
var someVarName_10 = 20;

alert(window["someVarName_10"]); //alert 20

</script>

Update: because OP edited the question.

<script>
num=10;
alert(window['someVar' + 'Name_' + num]); //alert 20
</script>

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();

How do I create a dynamically named global variable?

Thank you for the replies.

As suggested it should actually work and it does. My error lay elsewhere. I am aware of the risks of using global variables. Now I can work with MQTT topics like '+/presence/#' (containing information about the presence of different items detected by several sensors) with one flow.

How can I dynamically access a global variable in Node?

If you want an environment agnostic approach, for example, when writing code to work on both the browser and Node.js, you can do something like this in global code at the top of your JavaScript file:

var globalObject = typeof global === "undefined" ? this : global;

and then use globalObject similar to how you would window in the browser context and as you would use global in the Node.js context.

Note that you must declare a variable without var for it to be part of the global object in Node.js.

Javascript + build a dynamic variable name from a variable name and string

Here we build string and address window[yourvar] to increment, does this work for you

var player1InitStart = 0;var player2InitStart = 0;var player3InitStart = 0;var player4InitStart = 0;
//var playerID = event.target.id; // will return, player1, 2, 3, 4
document.querySelectorAll('div').forEach(div => { div.addEventListener('click', clickEvent);});
function clickEvent(event) { let playerID = `${event.target.id}InitStart`; window[playerID] += 1; logVars();}
function logVars() { console.log(player1InitStart); console.log(player2InitStart); console.log(player3InitStart); console.log(player4InitStart);}
<div id="player1">1</div><div id="player2">2</div><div id="player3">3</div><div id="player4">4</div>

How to complete a variable name with another variable

Use named indexing of the object to get a variable named property:

p.text(myObj["text" + btnNumber]);

Javascript lets you index properties of an object as if it were a dictionary (indexed via string names).

window[name] equivalent to dynamically access const and let declarations

Using indirect calls to eval

Accessing global const and let definitions can be done using an indirect call to eval. That is make eval the result of a comma separated expression or assign it to a variable first. If the syntactic access is not directly to the built-in eval function it's an indirect access, and indirect access executes in global scope.

You can also set global let variables by building script to perform the setting operation.

"use strict";let myVar =  "global variable myVar";
console.log( myVar);
(function myLibrary() {
const myVar = "local variable myVar";
const indirectEval = eval; var varName = "myVar";
console.log( eval(varName)); // direct call uses local scope console.log( indirectEval(varName)); // indirect call uses global scope
var result = "\"updated global variable even though shadowed\""; var js = varName + '=' + result; indirectEval(js);
// but trying to define a new let variable doesn't attach to global scope
var js2 ='let letVar2 = "let variable two"'; indirectEval( js2);})();console.log( myVar)
console.log( "letVar2: " + typeof letVar2);

How to make string act like a variable name?

Specify the dictionary first

Then you can take id's object... /p>

const dictionary = {
id1: {name: 'xxxx'},
id2: {name: 'yyyy'},
id3: {name: 'zzzz'},
};

const myfunc = (item)=>{
const idName = item.id;
const aName = dictionary[idName];
console.log(aName.name);
};
<div id="id1" onclick="myfunc(this)">one</div>
<div id="id2" onclick="myfunc(this)">one but 2</div>
<div id="id3" onclick="myfunc(this)">the third</div>

How to check dynamic global variables without using `window` in JavaScript?

It does not work because the variables are not in global scope, they are in scope of the window.onload function scope.

Sample Image

Your code is actually running like this:

window.addEventListener("load", function () {
var test1 = 'test1'; /* these are not global because of */
var test2 = 'test2'; /* running inside of window.onload */

function checkVariable(variableNameList) {
}

checkVariable(['test1', 'test2', 'test3']);
});

Change your code to run either in the head or at the end of the body. I forked your code to run in the head: https://jsfiddle.net/phrhxyzL/1/ and you get the results you expect.



Related Topics



Leave a reply



Submit