最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cannot read property of undefined - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question edited Apr 6, 2012 at 2:23 user1106925 asked Apr 6, 2012 at 2:20 SirSir 8,27717 gold badges88 silver badges154 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

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]){
发布评论

评论列表(0)

  1. 暂无评论