tags:

views:

118

answers:

3

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 = imgs[i];    //another line where i sucked in!

    }
}

preloader("asd.jpg|qwe.jpg|dorama.png");

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

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

var qwe[1] = 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};
+2  A: 

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 = imgs[i];
  }
}

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.

Nick Craver
Well, it will work, but the `img` variable's scope is the function, not the `for` loop.
Tim Down
@Tim - good point, updated though since it's not even needed their either unless you intended to use it.
Nick Craver
thanks for the answer, but why for loop? i mean when i use like this: var imgs = Array(); imgs[1] = "asd"; imgs[2] = "qwe"; /*and then*/ var i; for(i in imgs) { document.write(imgs[i] + "<br />"); } // is working...
dreamlore
@dreamlore - Click the great answer link for a lengthy explanation on this, basically you should never use a `for in` to iterate an array, as it's *enumerating* the object (and any *other* properties it may have) not *iterating* it.
Nick Craver
A: 

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

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

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.

orka