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>
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
How to create dynamic variables in JS?
You could also try this.
var count = 1; //Let this be your count variable.
var PersonString = "Person" + count; //Building a dynamic name for your variable
alert(PersonString); //Person1 will be alerted
window[PersonString] = "One";
alert(Person1); //One will be alerted.
Click here for the fiddle.
P.S : Here variables created dynamically will have a global scope.
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";
}
Related Topics
How to Accomplish an If/Else in Mustache.Js
How to Use Code from Script with Type=Module
Checking If Image Does Exists Using JavaScript
Getting a List of Associative Array Keys
Can't Access Cookies from Document.Cookie in Js, But Browser Shows Cookies Exist
How to Detect Right Mouse Click + Paste Using JavaScript
Promise Constructor with Reject Call VS Throwing Error
Updating an Input's Value Without Losing Cursor Position
How to Persist a Es6 Map in Localstorage (Or Elsewhere)
Checking Whether Something Is Iterable
How to Remove Element from Array in Foreach Loop
Sort Object Properties and JSON.Stringify
Angular App Has to Clear Cache After New Deployment