Reputation: 2329
I need to create dynamic variable name in js inside for loop
var counter = 0;
for(i=0; i<location.length; i++) {
...
var "marker_" + counter = new google.maps.Marker({
But when i expected to have variables marker_0,marker_1,marker_2,... i had this error
Error: SyntaxError: missing variable name
Source Code:
var "marker_" + counter = new google.maps.Marker({
Upvotes: 2
Views: 7876
Reputation: 1074148
Since this question is used as a duplicate target:
Use an array is good advice if the information you want to access is keyed numerically. If it isn't, you have two options:
Use an object and dynamic property access
Use a Map
(ES2015+)
You can access object properties using a string (or, in ES2015+, a Symbol) via brackets notation, so you can store information in an object to access later using strings/Symbols:
var theData = Object.assign(Object.create(null), {
x: "ecks",
y: "why"
});
var key = Math.random() < 0.5 ? "x" : "y";
console.log("key = " + key + ", theData[key] = " + theData[key]);
You can use a Map instead of an object even with strings or Symbols as keys, but unlike objects, Map keys can be any JavaScript value (except negative 0, but hey, good enough):
const theData = new Map([
["x", "ecks"],
["y", "why"]
]);
const key = Math.random() < 0.5 ? "x" : "y";
console.log("key = " + key + ", theData.get(key) = " + theData.get(key));
That example uses strings, but again, Map keys can be any type. A Map key can even be an object.
Upvotes: 0
Reputation: 136094
Well, "Use an array" is undoubtably the right answer here, however if you really want dynamic variables you need to decide the scope of them - the default would be window
and then you could do this:
var counter = 0;
for(i=0; i<location.length; i++) {
...
window["marker_" + counter] = new google.maps.Marker({
This can now be accessed with the same square bracket notation
window["marker_0"]...
or the dot notation
window.marker_0
Upvotes: 4
Reputation: 191729
Use an array:
var marker = [];
for (i=0; i < location.length; i++) {
marker[counter] = new google.maps.Marker({
Upvotes: 11