简体   繁体   中英

using a string to create a variable

I'm trying to create variables using strings.

I'm writing a script that will load images from a array of strings and I want to store those images in variables with the name of the used string.

This is the code so far:

var images = ["CrazyWolf.jpg", "CrazyWolf.jpg", "CrazyWolf.jpg", "CrazyWolf.jpg"];
var name = "";

function preload(path)
{
        img = new Image();
        img.src = path;
        img.onload = imageLoaded;
        return img;
};

function makeImages()
{
    for(var i = images.length; i > 0; i--)
    {
        source = images.shift();
        preload(source);
        var name = source.replace(".jpg", "Image");
        console.log(name);

        //make vars with as name, var name
        //Console.log(name); returns: CrazyWolfImage

        if(i==0) console.log("Loop ended");
    }
}

How do I use this name to create variables out of it?

Any help would be greatly apreciated!

Thanks!

What you ask for is quite easy. You can store the image as a property in the window object, and it can be accessed as a global variable:

function makeImages() {
  while (images.length) {
    source = images.shift();
    var name = source.replace(".jpg", "Image");
    window[name] = preload(source);
  }
}

However, creating variables dynamically isn't very useful, and it can have unforseen side effects. The code to use the variables either has to blindy use some variables depending on them being created, or access them dynamically which makes it pointless to have them as variables in the first place. The global namespace is already full of identifiers, so there is a risk that you use a name that already exists.

Instead of using the global namespace, create an object where you store the images by name. That way they are isolated from the global namespace and its existing identifiers. You don't even have to manipulate the name to make a valid identifier, a name like CrazyWolf.jpg works just fine to access properties:

var img = {};

function makeImages() {
  while (images.length) {
    source = images.shift();
    img[source] = preload(source);
  }
}

Now you can access the images dynamically from the object. Example:

document.getElementById('#ShowImage').src = img['CrazyWolf.jpg'].src;

You can also loop through the images in the object, which would not be possible if they were variables among all the existing in the global namespace:

for (image in img) {
  image.style.width = '200px';
}

Note: When looping through the properties in an object you can't rely on the order that they are processed. You would use an array instead of an object if you want to retain a specific order.

you can say something like this:-

eval("var number = 5");
console.log(number);

It'll print 5 as answer.

I think it will be helpful.

You can't create non-global variables with constructed names without using eval() (which would be a pretty bad idea), but you can create object properties:

var imgs = {};
for(var i = images.length; i > 0; i--)
{
    source = images.shift();
    preload(source);
    var name = source.replace(".jpg", "Image");
    console.log(name);
    imgs[name] = whatever;
}

eval() should be avoided because it makes internal code optimization impossible, if not for oft-discussed aesthetic reasons.

Global variables are properties of the global context ( window ) so if you want global variables (why?) you can use that instead of a local object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM