Sir
Sir

Reputation: 8277

Cannot read property of undefined

I'm looping my object data but am getting this undefined value.

Not sure why but was hoping some one can explain.

My object is like this:

//globally set
var sdata = {"4":{"7":["1","7","3","3"]},"3":{"3":["2","8","1","1"]}};

And i loop the object like this:

function is_occupied(position) {
    for (var x in sdata) {
        for (var y in sdata) {
            // error's here Cannot read property '2' of undefined
            var ex = sdata[x][y][2] > position.block_width ? (sdata[x][y][2] + (sdata[x][y][2] - position.block_width)) : sdata[x][y][2],
            var ey = sdata[x][y][3] > position.block_height ? (sdata[x][y][3] + (sdata[x][y][3] - position.block_height)) : sdata[x][y][3];
            if (position.x >= sdata[x][y][2] && position.x <= ex && position.y >= sdata[x][y][3] && position.y <= ey) {
                alert('hit');
            }
        }
    }
}

I'm wondering why it would say its undefined ? =/ Can't work it out. Its suppose to be getting position [2] in the array data of that object.

Upvotes: 0

Views: 4879

Answers (1)

chrisn
chrisn

Reputation: 2135

I believe you want to be looping over sdata[x], not sdata in your inner loop:

function is_occupied(position) {
    for(var x in sdata){
     for(var y in sdata[x]){

Upvotes: 6

Related Questions