javascripthtml5-canvasanimate-cc

Trying to do an array within an array in animate CC (html5 canvas)


var Home = this;
creategame();
var beasts = [];
function creategame() {
for (i=0;i<4;i++)
{

beasts[i][0] = "lib.ojb"+i.toString()+"()";
beasts[i][1] = 150+(i*125);
}

for (i=0;i<4;i++)
{
var n = new beasts[0][0][0];
    n.x = beasts[i][1];
    n.y = 350;
    n.name = "animal"+i.toString();
    stage.addChild(n);
    n.addEventListener("pressmove", dragFunc);
    n.addEventListener("pressup",release);

}
}   

Is it impossible to write the array as 'var beasts' and then expect the software to create the subarrays when told 'beasts[i][0]=something' resulting in it putting beasts = [[something,[]]] basically? the console keeps telling me 'cannot read property of undefined'


Solution

  • You need to create an array for the beasts items. You can't assign property values to something that doesn't exist.

    for (i=0;i<4;i++){
        beasts[i] = [];
        beasts[i][0] = "lib.ojb"+i.toString()+"()";
        beasts[i][1] = 150+(i*125);
    }
    

    Edit: here is another way to write it.

    for (i=0;i<4;i++){
        beasts[i] = [
            "lib.ojb"+i.toString()+"()",
            150+(i*125)
        ];
    }