错误; (数组)speelVeld未定义

时间:2012-12-03 14:06:58

标签: javascript error-handling

我需要在我的学校为一个项目制作一个基于平铺的游戏,并遇到一个我无法解决的“关键”错误。

这是我的剧本:

function init(){
var speelVeldBreedte;
var speelVeldHoogte;
var speelVeld = [
    [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1]
];

var speelTerrein = document.getElementById("speelterrein");
}

speelVeldBreedte=speelVeld[0].length; 
speelVeldHoogte=speelVeld.length;

var schaalTerrein = 20;
speelTerrein.width = speelVeldBreedte * schaalTerrein; 
speelTerrein.height = speelVeldHoogte * schaalTerrein;


var ctx = speelTerrein.getContext("2d");
ctx.fillStyle = "white";
ctx.fillRect(0,0,speelTerrein.width,speelTerrein.height);
    for (var y=0; y<speelVeldHoogte;y++){
        for (var x=0;x<speelVeldBreedte;x++){
            var steen = speelVeld[y][x];
            if (steen> 01){
                ctx.fillStyle = "rgb(100,0,0)";
                ctx.fillRect(x*schaalTerrein,y*schaalTerrein,schaalTerrein,schaalTerrein);
            }
        }
    }

这是我得到的错误:

uncaughtReferenceError: speelVeld is not defined.

指的是第32行:

speelVeldBreedte=speelVeld[0].length;

我希望有人能告诉我如何解决这个错误以及究竟是什么问题。

提前致谢, 雷米

2 个答案:

答案 0 :(得分:1)

您已在speelVeld函数的正文中定义了init(),并且您在第32行的调用超出了该函数 - 因此,JS无法&#34;请参阅&#34;变量,因为它超出了范围。

答案 1 :(得分:0)

spelVeld(以及所有变量)在init()函数中作用域。

您可以在此处阅读有关范围:http://coding.smashingmagazine.com/2009/08/01/what-you-need-to-know-about-javascript-scope/