开发者

how to load a 2d array in js?

Okay, I'm trying to load a 2d array and having some problems. Here's my code:

var blockSize = 30;

var level = new Array(new Array(0, 1, 0, 1, 0, 1, 0, 1, 0, 1), new Array(1, 0, 1, 0, 1, 0, 1, 0, 1, 0));

var blockArray = new Array(1);
blockArray[0] = new Array(1);

function readLevel() {
    for (var i = 0; i < level.length; i++) {
        for (var j = 0; j < level[i].length; j++) {
            var tempImg = new Image();
            tempImg.src = "images/bloc开发者_StackOverflowk.png";
            blockArray[i][j] = new block(i * blockSize, j * blockSize, level[i][j], false, false, tempImg);

            //throw('blockArray['+i+']'+j+'] = ' + level[i][j]);
        }
    }
}

And here is my error:

Firebug's log limit has been reached. 0 entries not shown.      Preferences  
blockArray[i] is undefined
[Break On This Error] blockArray[i][j] = new block(i *...level[i][j], false, false, tempImg); 

How do I fix this?


Your outer loop, on i, will go from 0..1 (inclusive). You're never setting blockArray[1] to anything, and so it's undefined. So your blockArray[i][j] = ... line will fail because you can't index into an undefined value (blockArray[i] is undefined when i = 1).

I'm not entirely sure what your code is meant to do, but this should get you close, anyway:

var blockSize = 30;

var level = [
                [0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
                [1, 0, 1, 0, 1, 0, 1, 0, 1, 0]
            ];

var blockArray = [];

function readLevel() {
    for (var i = 0; i < level.length; i++) {
        blockArray[i] = []; // Create the second level for this index
        for (var j = 0; j < level[i].length; j++) {
            var tempImg = new Image();
            tempImg.src = "images/block.png";
            blockArray[i][j] = new block(i * blockSize, j * blockSize, level[i][j], false, false, tempImg);

            //throw('blockArray['+i+']'+j+'] = ' + level[i][j]);
        }
    }
}

Note that I've also ditched the new Array(n) syntax in favor of array literal syntax. I think it's clearer for what you're doing here.

It's important to realize that JavaScript doesn't really have arrays, and it certainly doesn't have 2D arrays. JavaScript "arrays" are really just objects that give special treatment to a class of property names (ones consisting entirely of digits) and that have a special length property. (And, of course, they have all the functions they inherit from Array.prototype.) More here.


Try to add between your two for-loops these line

blockArray[i] = new Array();

to create the second level array.

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜