How do I declare and use dynamic variables in JavaScript?

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.


Solution 1:

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

Solution 2:

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

Solution 3:

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";     

Solution 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.