0

I have this code

    var a = new Image();
    a.src = objects.a.image;

    var b = new Image();
    b.src = objects.b.image;

    var x = new Image();
    x.src = objects.x.image;

I have about 10 images like this, is there any better way to load it into variables?

3
  • You can use array style Commented Mar 28, 2013 at 9:00
  • var objects = { 'a': { 'image': '1.png' }} Commented Mar 28, 2013 at 9:01
  • Few different ways, perhaps a function which you pass the image src into as a paramater and then the function returns you your created img. Or loop over your object creating an image for each src - depends what your object looks like. Commented Mar 28, 2013 at 9:01

4 Answers 4

1

This should work

for(var i in objects)
{
    if(objects[i].image)
    {
        var oImage = new Image();
        oImage.src = objects[i].image;
        // if you need the Image object you can store it somewhere
        objects[i].oImgObject = oImage;
     }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Assuming objects contains just images, try this:

var imageList = [];
for (var i in objects) {
    var obj = objects[i];
    var img = new Image();
    img.src = obj.image;
    imageList.push(img);
}

1 Comment

Or if it contains more than images, add a if(obj.image) { /* set img.src */ }
0

You normally would use an array to store your images.

For example :

var arr = [];
for (var c='a'.charCodeAt(0); c<='x'.charCodeAt(0); c++) {
     var img = new Image();
     img.src = objects[String.fromCharCode(c)].image;
     arr.push(img);
}

If you really need to add them as variables to the global context, you might do this :

for (var c='a'.charCodeAt(0); c<='x'.charCodeAt(0); c++) {
     var img = new Image();
     var name = String.fromCharCode(c);
     img.src = objects[name].image;
     window[name] = img; // better use somthing's else than window...
}

Note that depending on what really is objects, there might be a more straightforward solution.

Comments

0

You can iterate through the properties of your objects object. Creating a new image per iteration, giving it the source of the property on your objects. Then adding it to the array:

Demo

var arrayOfImg = [];

for(var propt in objects){
    var image = new Image();
    image.src = objects[propt].image;
    arrayOfImg.push(image)
}

console.log(arrayOfImg);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.