Xlander
Xlander

Reputation: 1331

Object[key] returns undefined (strange)

I've had a weird behaviour from an object.

var canvas = document.createElement('canvas');
canvas.style.display = 'none';
document.body.appendChild(canvas);

var ctx = canvas.getContext('2d');
//imgObj is an Image Object
ctx.drawImage(imgObj, 0, 0);

//inserting(caching) the image data in the spriteData object
var spriteCoordinates = coordinates.spriteCoordinates; 
//coordinates.spriteCoordinates has keys in integer

for(var i in spriteCoordinates){
    var x = spriteCoordinates[i].x,
        y = spriteCoordinates[i].y,
        w = spriteCoordinates[i].w,
        h = spriteCoordinates[i].h;

    var imageData = ctx.getImageData(x, y, w, h);

    spriteData[i] = imageData;
}

When I console.log spriteData, I get:

Object { }

enter image description here

When I click on it, I get:

0: {
    width: int,
    height: int,
    data: array()
}// I've put int and array just for representation

enter image description here

But when I console.log spriteData[0] (spriteData['0']), I get undefined. And I've even tried to console.log Object.keys(spriteData), but I get an empty array.

Can someone tell me please what's going on?

EDIT

After some manipulation I found that this was cause when I put this function in the onload method of the Image object. But outside of it the object was normal.

Upvotes: 2

Views: 1817

Answers (1)

Madara's Ghost
Madara's Ghost

Reputation: 174957

Instead of using the for..in loop, use the more semantic .map():

var spriteData = Object.keys(spriteCoordinates).map(function(key) {
    var item = spriteCoordinates[key];
    return ctx.getImageData(item.x, item.y, item.w, item.h);
});
  • Object.keys(spriteCoordinates).map(fn) - Take an array made of the keys of the spriteCoordinates object, and transform it into an array
  • fn is a function, .map() will iterate over the array, apply the function on each item, and construct a new array from the result.

The result is a new array which you directly assign to spriteData.

Upvotes: 2

Related Questions