javascript – Variables Variable (Creating variable with the name of another variable) – Education Career Blog

i want to create a new variable with a variable name,
for example:

function preloader(imglist) {

  var imgs = imglist.split("|");

    for (i in imgs) {

      var img_{i} = new Image;  //this is the line where i sucked in!
      img_{i}.src = imgsi;    //another line where i sucked in!



i try to use arrays but, hmm.. how can i say…

var qwe = new Array();
qwe1 = "asd"; //or not! whatever...

var qwe1 = new Image; // it didnt work!

in php u can use like this:

$var1 = "test";
$var2_{$var1} = "test last";
echo $var2_test; //or...
echo $var2_{$var1};


You don’t need to do that here, each Image can be stored and overwritten to get the same preload effect, however just this will work:

function preloader(imglist) {
  var imgs = imglist.split("|");
  for (var i=0; i<imgs.length; i++) {
    new Image().src = imgsi;

Note that I changed this from a for in loop, you should use a normal index for loop when iterating over an array (not enumerating) CMS has a great answer here explaining this in more detail.



You can achive your goal by using Eval() function as shown below;

var data = "testVariable";
eval("var temp_" + data + "= new Array();");
temp_testVariabletemp_testVariable.length="Hello World";
alert("Array Length: " + temp_testVariable.length);
alert("Array Data: " + temp_testVariable0);

Of course it doesn’t mean that is the right solution. I have just given the information about the ability.

Here is the article that contains the above sample and an alternative solution using Window object.

Leave a Comment