espace3d espace3d - 5 months ago 29
Javascript Question

javascript acces an item of an array?

I'm a beginner with javascript used with PIXI.

I don't know how to format an array with row and line. I try this snippet but when i want to access a specific value of this array :

alert(graphics[2][1].position.x)


I have this error :

Uncaught TypeError: Cannot read property '1' of undefined(anonymous function) @ main.js:40


Here my complete snippet :

var renderer = PIXI.autoDetectRenderer(800, 600,{backgroundColor : 0x1099bb});
document.body.appendChild(renderer.view);

var stage = new PIXI.Container();

var container = new PIXI.Container()

stage.addChild(container);

for (var j = 0; j < 5; j++) {
for (var i = 0; i < 5; i++) {
var graphics = new PIXI.Graphics();

graphics.beginFill(0xFF3300);
graphics.lineStyle(4, 0xffd900, 1);
graphics.drawRect(0,0,10,10);
graphics.position.x= 40 * i;
graphics.position.y=40 * j;
container.addChild(graphics);
};
};

alert(graphics[2][1].position.x)//here my error

container.x=100
container.y=100
container.scale.x=container.scale.y=.1;

animate();

function animate() {
requestAnimationFrame( animate );

container.rotation += .1;
renderer.render(stage);
}

Answer

If you want to have 2d array then you need to use this code:

var graphics = [];
for (var j = 0; j < 5; j++) {
    graphics[j] = [];
    for (var i = 0; i < 5; i++) {
        graphics[j][i] = new PIXI.Graphics();

        graphics[j][i].beginFill(0xFF3300);
        graphics[j][i].lineStyle(4, 0xffd900, 1);
        graphics[j][i].drawRect(0,0,10,10);
        graphics[j][i].position.x = 40 * i;
        graphics[j][i].position.y = 40 * j;
        container.addChild(graphics[j][i]);
    };
};

then you will be able to call this:

alert(graphics[2][1].position.x);