我正在尝试显示使用此代码的级别...

levelArray[0] = ["player", "empty", "empty", "empty", "wall", "wall", "empty",
    "empty", "wall", "wall", "empty", "empty", "empty","empty",
    "empty", "empty", "empty", "wall", "empty", "wall", "wall",
    "wall", "wall", "empty", "wall", "empty", "wall", "empty",
    "box", "wall", "empty", "wall", "empty", "empty", "empty",
    "empty", "empty", "empty", "wall", "wall", "wall", "empty",
    "wall", "wall", "empty", "empty", "ghost", "wall","ghost"];

for(var i = 0; i < edge; i++)
{
    for(var j = 0; j < edge; j++)
    {
        switch(levelArray[i])
        {
            case "empty":   // empty location
                ctx.drawImage(emptyTile, currentX, currentY);
                break;
            case "wall":    // wall block
                ctx.drawImage(wallTile, currentX, currentY);
                break;
            case "box":     // box block
                ctx.drawImage(boxTile, currentX, currentY);
                break;
            case "ghost":   // enemy sprite
                ctx.drawImage(ghostTile, currentX, currentY);
                break;
            case "player":  // player sprite
                ctx.drawImage(playerTile, currentX, currentY);
                break;
        }
        currentX += elementEdge;
    }
    currentY += elementEdge;
}


但是我在切换行“未捕获的TypeError:无法读取未定义的属性'0'”上收到错误,但我不太了解。

编辑:
边缘是这样定义的

edge = Math.sqrt(levelArray.length)

最佳答案

您没有使用内部循环。我相信您想要这样:

switch(levelArray[i][j])




your source code中,该片段位于setupCanvas函数内部,并以levelArray作为参数。由于调用setupCanvas时没有传递任何内容,因此将其视为undefined。因此,您得到的错误。

关于javascript - 数组困惑,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18212156/

10-12 13:05