byAdam
byAdam

Reputation: 61

unidentified when alerting array

When I run this it alerts unidentified whenever worldgeny == 400 and i do not know why. If i alert worldgeny in the same place it alerts NaN. I may have not explained this very well. if you are confused just ask. My code is messy I know this is just a test for me personally Thanks in advance

var addy;
var worldgeny = parseInt(200);
var mul5 = parseInt(0);
var endhole;
var holegen;
var sizeh = 30;
var sizew = 30;
var savey = [];

function cworld() {
    mul5++;
    posX++;
    canvasContext.drawImage(imageGround, posX, worldgeny, 1, 400);
        if(mul5 % 30 == 0){
            if(worldgeny==400){
                endhole = mul5/30;
                endhole = endhole - 1;
                worldgeny=savey[endhole];
                alert(savey[endhole])
            }
            addy = parseInt(Math.floor((Math.random()*30)-17));
            holegen = parseInt(Math.floor((Math.random()*5)));
            worldgeny += addy;
            if(holegen==1){
                worldgeny = 400;
            }
            savey.push(worldgeny);
        }
    }
setInterval(cworld, 1);

Upvotes: 1

Views: 64

Answers (1)

Bucket
Bucket

Reputation: 7521

var savey = [];

This is an empty array.

alert(savey[endhole])

No matter what endhole is, this evaluates to undefined, since savey.length is 0.

savey.push(worldgeny);

This actually adds elements to savey. Until you do this, every time you try to reference an element of that array, it will return undefined.

Furthermore, make sure endhole is a valid index. If savey has a length of N, make sure endhole is between 0 and N-1.

EDIT: It looks like the real culprit is your assignment of endhole. First you say endhole = mul5/30, but mul5 is 0, so now endhole is 0. Right after this, you decrement it, leaving the value of endhole to be -1, which is an invalid index in the array.

I'm not sure what logic you want to implement to fix this, but your index must be 0 or greater. Referencing an array's index of -1 will always result in undefined.

Upvotes: 2

Related Questions