简体   繁体   English

javascript-遍历二维数组

[英]javascript - iterating over bidimensional arrays

I am trying to write a javascript program that renders an 8x8 grid of dirt tiles on an HTML5 canvas. 我正在尝试编写一个JavaScript程序,以在HTML5画布上呈现8x8的污垢图块网格。 However, when I run this code it throws up error messages when running the draw_terrain() function and it appears to be a problem with the blockArray.length component. 但是,当我运行此代码时,在运行draw_terrain()函数时会引发错误消息,并且blockArray.length组件似乎有问题。 Can someone explain to me how to fix this problem? 有人可以向我解释如何解决此问题吗? Thanks in advance. 提前致谢。

//Define initial canvas variables and images

var canvas;
var ctx;
var WIDTH = 800;
var HEIGHT = 800;
var dirt = new Image();
dirt.src = 'dirt.png';

//Function called to initialise canvas variables and run draw on interval

function init(){
    canvas = document.getElementById('myCanvas');
    ctx = canvas.getContext('2d');
    return setInterval(draw, 15);
}

//Function that generates an 8x8 Array called blockArray

function gen_terrain(){

var blockArray = new Array(8);

for(var i=0; i<blockArray.length; i++) {
    blockArray[i] = new Array(8);
    for(var j=0; j<blockArray[i].length; j++){
        blockArray[i][j] = 0;
    };
};
}

//Function that returns a random number between a min and max

function randomRange (min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function draw_terrain(){
    for(var i=0; i<blockArray.length; i++) {
        for(var j=0; j<blockArray[i].length; j++){
            ctx.drawImage(dirt,(n-1)*32,(j-1)*32);
        };
    };
}

function draw(){
    draw_terrain();
}

gen_terrain();
init();

Your problem, as other people have explained is that the variable you are using the build the array will not exist by the time the draw occurs. 正如其他人所解释的那样,您的问题是,正在使用构建数组的变量在绘制发生时将不存在。 Just place your array declaration outside of the function and your issue will go away. 只需将数组声明放置在函数之外,问题就会消失。

See comment below: 请参阅下面的评论:

function init(){
    canvas = document.getElementById('myCanvas');
    ctx = canvas.getContext('2d');
    return setInterval(draw, 15);
}

//Function that generates an 8x8 Array called blockArray
var blockArray = []; // <== has to be global (outside function).

function gen_terrain(){
    // Not here -> var blockArray = [];
    for(var i=8; i--;) {
        blockArray[i] = [0,0,0,0,0,0,0,0];
    };
}

Example

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM