user1768788
user1768788

Reputation: 1365

Value not getting added to array?

Simple question which seems impossible for me because I'm just staring in the code.

Basicly I have this function, I call it X amount of times and it should put all the created divs in a array called world which I've declared outside of the function.

However, if I try to use one of these values they are "undefined".

var world = [];


function newTile(x, y, size, rotX, rotY, rotZ, tranX, tranY, tranZ, color) {

    var tile = document.createElement('div');
    tile.className = "tile";
    tile.style.width = size+"px";
    tile.style.height = size+"px";
    tile.style.webkitTransform = 
        "rotateX("+rotX+"deg)"+
        "rotateY("+rotY+"deg)"+
        "rotateZ("+rotZ+"deg)"+
        "translateX("+tranX+"px)"+
        "translateY("+tranY+"px)"+
        "translateZ("+tranZ+"px)";
    tile.style.transform = 
        "rotateX("+rotX+"deg)"+
        "rotateY("+rotY+"deg)"+
        "rotateZ("+rotZ+"deg)"+
        "translateX("+tranX+"px)"+
        "translateY("+tranY+"px)"+
        "translateZ("+tranZ+"px)";
    if (x == 0 && y == 0) {
        color="rgba(255,255,0,0.5)";
        pathStart = tile;
        pathCur = tile;
    }
    tile.style.backgroundColor = color;

    tile.data = {
        x:x,
        y:y,
        blacklist:0
    }

    tile.onclick = function() {
        worldOri(null,null,null, -this.data.x*128 - 64, null, -this.data.y*128 - 64);
    };

    if (debug) tile.textContent = x+", "+y;

    document.getElementById('world').appendChild(tile);
    world[x] = [];
    world[x][y] = tile;
}

Lets say I do something like:

newTile(2,6,128,90,0,0,2*128,0,6*128, "rgba(255,125,0,0.5)");

This works as intended and surely creates a div, placing it "in" another div with the id "world" and SHOULD add the div to the array "world" at [2][6]. If I now try to do something with the div, for example change color:

world[2][6].style.backgroundColor = "rgba(255,0,0,0.5)";

It returns as undefined, which I assume is that the actual adding to the "world" array didn't work, please help.

Upvotes: 0

Views: 69

Answers (1)

Felix Kling
Felix Kling

Reputation: 817238

world[x] = []; will assign an empty array world[x] every time you make a call to newTile, thus "removing" all existing tiles from world[x]. Only initialize it if it doesn't exist yet:

world[x] = world[x] || [];

Upvotes: 2

Related Questions