开发者

Retrieving spcecific JSON values related to a loop

I'm making a browser based game which involves a map. To render the map I am using two loop to retrieve the map data from a json set. The json set looks like this (Example):

var map = {
'y1':{'x1':{'type':'grass'}, 'x2':{'type':'water'}, 'x3':{'type':'grass'}},
'y2':{'x1':{'type':'grass'}, 'x2':{'type':'water'}, 'x3':{'type':'grass'}},
'y3':{'x1':{'type':'grass'}, 'x2':{'type':'water'}, 'x3':{'type':'grass'}},
'y4':{'x1':{'type':'grass'}, 'x2':{'type':'water'}, 'x3':{'type':'grass'}},
'y5':{'x1':{'type':'grass'}, 'x2':{'type':'water'}, 'x3':{'type':'grass'}}
};

There is two loops. One with the variable i, which is associated with the Y axis, and ii, which is associated with the X axis. How would I get the json data with the tag like map.yi.xii.type? I've been trying to do this for days but I'm very new to json and can't find any answers. The code for my map is below. Any help would be appreciated. If I've been unclear please let me know and I'll try and give a better exp开发者_JAVA技巧lanation.

var create = '';
for(i=0; i <= 4; i++)
{
    var hello="x1";
    create += '<table cellpadding="0" cellspacing="0"><tr>';
    for(ii=0; ii <= i; ii++){
        if(i==4 && ii==2){
            create += '<td class="'+map.y1.x1.type+'" align="center" valign="center"><img src="images/map/dot.gif"/></td>';
        }
        else{
            create += '<td class="'+map.y1.x2.type+'"/>';
        }
    }
    create += '</tr></table>';
}
for(x=4; x >= 0; x--)
{
    create += '<table cellpadding="0" cellspacing="0"><tr>';
    for(xx=0; xx < x; xx++){
        create += '<td class="'+map.y1.x2.type+'"/>';
    }
    create += '</tr></table>';
}

Project Link.


When you wrote:

map.yi.yii.type

I assume you meant:

map.yi.xii.type

If so, you could use concatenation inside square brackets.

map['y'+i]['x'+ii].type;

...so if i == 1 and ii == 3, you'll effectively be doing:

map.y1.x3.type;


Sounds like you need to do something like this:

map[y+i][x+ii]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜