How do I declare and use dynamic variables in JavaScript?
Asked Answered
A

9

41

Suppose I need to declare a JavaScript variable based on a counter, how do I do so?

var pageNumber = 1;
var "text"+pageNumber;

The above code does not work.

Averi answered 10/5, 2011 at 3:11 Comment(0)
B
74

In JavaScript (as i know) there are 2 ways by which you can create dynamic variables:

  1. eval Function
  2. window object

eval:

var pageNumber = 1;
eval("var text" + pageNumber + "=123;");
alert(text1);

window object:

var pageNumber = 1;
window["text" + pageNumber] = 123;
alert(window["text" + pageNumber]);
Bernard answered 10/5, 2011 at 3:27 Comment(3)
For example, Ihave array in dynamic var window["text" + pageNumber] - how to get length of array?Willams
window["text" + pageNumber].lengthManpower
You may probably use any object, not just the window one: see Mark Kahn answer.Carditis
B
8

How would you then access said variable since you don't know its name? :) You're probably better off setting a parameter on an object, e.g.:

var obj = {};
obj['text' + pageNumber] = 1;

if you -really- want to do this:

eval('var text' + pageNumber + '=1');
Beyer answered 10/5, 2011 at 3:17 Comment(1)
There are lots of ways you might access said vars: looping through a number set where vars are named var1, var2, var3. Or retrieving a unknown set vars and loading them dynamically by looping through a json object and updating global vars, im sure there are lots more scenariosEstelleesten
T
6

I don't think you can do it sing JavaScript.I think you can use an array instead of this,

 var textArray=new Array();
    textArray[pageNumber]="something";     
Turtledove answered 10/5, 2011 at 3:16 Comment(0)
T
4

Assuming that the variable is in the global scope, you could do something like this:

var x = 1;
var x1 = "test"
console.log(window["x" + x]); //prints "test"

However, a better question might be why you want such behaviour.

Thorathoracic answered 10/5, 2011 at 3:16 Comment(0)
T
2

You could also wrap your counter in an object:

var PageNumber = (function() {
  var value = 0;
  return {
   getVal: function(){return value;},
   incr: function(val){
            value += val || 1;
            this['text'+value]=true /*or some value*/;
            return this;
         }
   };
})();

alert(PageNumber.incr().incr().text2); //=>true
alert(PageNumber['text'+PageNumber.getVal()]) /==> true
Thecla answered 10/5, 2011 at 5:57 Comment(0)
D
1

It can be done using this keyword in JS:

Eg:

var a = [1,2,3];

for(var i = 0; i < a.length; i++) {
  this["var" + i] = i + 1;
}

then when you print:

var0 // 1
var1 // 2
var2 // 3
Dihybrid answered 28/3, 2018 at 7:47 Comment(0)
T
0

I recently needed something like this.

I have a list of variables like this:

var a = $('<div class="someHtml"></div>'),b = $('<div class="someHtml"></div>'),c = $('<div class="someHtml"></div>');

I needed to call them using another variable that held a string with the name of one of these variables like this:

var c = 'a'; // holds the name of the wanted content, but can also be 'b' or 'c'

$('someSelector').html(eval(c)) // this will just use the content of var c defined above

Just use eval to get the variable data.

I just did

Tankard answered 25/9, 2013 at 14:27 Comment(0)
P
0

I know a lot of the other answers work great, such as window["whatever"] = "x"; but I will still put my own answer here, just in case it helps.

My method is to use Object.assign:

let dict = {};
dict["test" + "x"] = "hello";
Object.assign(window, dict)
Precipitant answered 6/11, 2021 at 4:53 Comment(0)
D
0

a little improvement over bungdito's answer, use the dynamic variable dynamically

var pageNumber = 1;
eval("var text" + pageNumber + "=123456;");
eval(`alert(text${pageNumber})`);

note: usage of eval is strongly discourgae

Doukhobor answered 17/12, 2022 at 17:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.