【发布时间】:2012-03-21 10:57:25
【问题描述】:
我对使用 JSON 对象还很陌生,我有点卡住了。
我有一个从这个数组转换而来的 JSON 对象:
Array
(
[status] => success
[id] => 1
[name] => Zone 1
[description] => Awesome zone deze..
[tiles] => Array
(
// Column for the tile grid
[0] => Array
(
// Row for the tile grid
[0] => Array
(
[tileID] => 1
[rotation] => 0
)
[1] => Array
(
[tileID] => 1
[rotation] => 0
)
// Etc..
)
[1] => Array // etc.. etc..
)
)
我使用这个对象为我的 HTML5 Canvas 游戏渲染出一个等距网格。我正在构建一个地图编辑器并在地图上放置更多图块,我必须向这个 json 对象添加值。
这就是我在 PHP 中的做法:
mapData[column][row] = array(
'tileID' => 1,
'rotation' => 0
);
所以我的问题是,如何在 javascript 中使用 JSON 对象来实现这一点?
提前致谢!
尼克
更新
我遇到了一个错误:
can't convert undefined to object
mapDataTiles[mouseY][mouseX] = { tileID: editorSelectedTile, rotation: 0 };
这是我用于单击并将新图块保存到 JSON 对象的代码。起初我虽然我的一个参数是'未定义',所以我将它们记录到控制台,但它们完美地出来了..
// If there is already a tile placed on these coordinates
if( mapDataTiles[mouseX] && mapDataTiles[mouseX][mouseY] )
{
mapDataTiles[mouseX][mouseY]['tileID'] = editorSelectedTile;
}
// If there is no tile placed on these coordinates
else
{
mapDataTiles[mouseX][mouseY] = { tileID: editorSelectedTile, rotation: 0 };
}
我的变量有以下值:
MouseX: 5
MouseY: 17
tileID: 2
另外一个奇怪的事实是,对于某些坐标,它确实可以工作并将新数据保存到数组中。
更新 2
经过几个小时的反复试验和错误编码,我想出了一个解决方案!
还是感谢大家的帮助!
如果有人好奇,我很乐意展示我的代码。到目前为止,我所拥有的是能够向任何方向扩展世界地图以获得无限数量的瓷砖。 :D
Cya
【问题讨论】:
标签: javascript json object add