Variables Variables (Creating a variable with the name of another variable)

I want to create a new variable with the 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 am trying 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 be used like this:

$var1 = "test";
$var2_{$var1} = "test last";
echo $var2_test; //or...
echo $var2_{$var1};
+3
source share
3 answers

You do not need here, each Imagecan be saved and overwritten to get the same preload effect, but only 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 loop for in, you should use a loop with a normal index forwhen iterating over an array (without listing) CMS has an excellent answer here , explaining this in more detail.

+2

You can achieve your goal using the 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, this does not mean that this is the right decision. I just gave information about the ability.

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

0
source

Source: https://habr.com/ru/post/1770336/


All Articles