Use Dynamic Variable Names in JavaScript

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 dynamic variable names inside a loop?

Use an array for this.

var markers = [];
for (var i = 0; i < coords.length; ++i) {
markers[i] = "some stuff";
}

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>

Create dynamic variable names based on count result

solution is to use eval, but It's nasty code, Avoid using 'eval', just use an array or object.

1, eval solution:

const ElementCount = 2;

for (let i = 1; i <= ElementCount; i++) {
eval("let SampleVariable[" + i + "] = 'test'");
}

2, array solution:

const ElementCount = 2;
let Variables = []
for (let i = 1; i <= ElementCount; i++) {
Variables["SampleVariable" + i] = "test";
}

3, object solution:

const ElementCount = 2;
let Variables = {}
for (let i = 1; i <= ElementCount; i++) {
Variables["SampleVariable" + i] = "test";
}

JavaScript Dynamic Variable Names

You can only do that with bracket notation, which means you have to attach the variables to something.

The global scope would be window, so that would be window['hello' + newCount], but polluting the global namespace with a bunch of random properties doesn't sound like a good idea, so using an object seems better

var vars = {};
var newCount = parseInt($('#hello').html(), 10);

$('.hello').click(function(){
newCount++;
vars['hello' + newCount] = '<p>Hello World</p>';
});

alert( vars['hello1'] );

FIDDLE



Related Topics



Leave a reply



Submit