Cains
Cains

Reputation: 901

Variable in for loop is undefined?

When Update() is ran I get an error stating that map[x] is undefined at "map[x][y] = rawmap[rawmapcount];" and I'm not sure why?

var currentuser;
var map = new Array(63);
for(x = 0;x < 36;x++) {
    map[x] = new Array(35);
}

function Update(login) {
    $.post("server.php",{update:1,login:login},function(data) {
        if(data == 0) {window.location.href = "WEBSITE";}
        else {
            var rawdata = data.split("[BRK]");
            currentuser = rawdata[0];
            var rawmap = rawdata[1].split("|");
            var rawmapcount = -1;
            var x;
            var y;
            for(x = 0;x < 64;x++) {
                for(y = 0;y < 36;y++) {
                    rawmapcount++;
                    map[x][y] = rawmap[rawmapcount];
                }
            }
        }
    });
}

Update(1);
//setInterval(function() {Update(0);},500);

Upvotes: 0

Views: 763

Answers (1)

Ted Hopp
Ted Hopp

Reputation: 234867

You're initializing the first 36 positions of map, but you're trying to access 64 positions as if they were all initialized.

for(x = 0;x < 36;x++) { // <= Note the range!
    map[x] = new Array(35);
}
    . . .
        for(x = 0;x < 64;x++) { // <= Note the range!
            for(y = 0;y < 36;y++) {
                rawmapcount++;
                map[x][y] = rawmap[rawmapcount];
            }
        }

Also, your y range is 36, not 35. However, that doesn't cause an error because JavaScript will automatically extend the range of an array. In fact, you could initialize each element of map with:

map[x] = [];

Upvotes: 5

Related Questions