Dominic Sore
Dominic Sore

Reputation: 385

Switch handle multidimensional array. Unexpected result

so I have a javascript function that pushes a multidimensional array value to a parameter like so:

function mouseHandle(x,y){
    for(var i=0; i<buttonPos.length; i++){
        if(x>buttonPos[i][0] && x<buttonPos[i][2]){
            if(y>buttonPos[i][1] && y<buttonPos[i][3]){
                eventButton(buttonPos[i][4]);
            };
        };
    };
};

This pushed buttonPos[i][4] to the eventButton function which is:

function eventButton(d){
    switch(d){
        case 0: // STARTBUTTON
            alert("Button");
            break;
        default:
            alert("NoButton");
    };
};

The array is set in the drawButton function as so:

function drawButton(x,y,width,height,string,event){
    xCenterButton=x+(width/2);
    yCenterButton=y+(height/2);

    ctx.fillStyle="rgba(242,255,195,1)";
    ctx.fillRect(x,y,width,height);

    ctx.rect(x,y,width,height);
    ctx.fillStyle="rgba(0,0,0,1)";
    ctx.stroke();

    ctx.font="25px Arial";

    fontSize = getFontSize();
    centerNum = fontSize/4;

    ctx.fillStyle="rgba(0,0,0,1)";
    ctx.textAlign="center";
    ctx.fillText(string,xCenterButton,yCenterButton+centerNum);

    buttonPos.push([[x],[y],[x+width],[y+height],[event]]);
};

I then call that function in the menuStart function as so:

function menuStart(){
    drawButton(getCenterX(100),getCenterY(50),100,50,"Start",0);
};

So the mouseHandle function DOES give the eventButton function a parameter of 0 as expected (I alerted the 'd' parameter within the default case). However it's as if the switch statement doesn't recognise the 0 as it uses the default case and alerts 'NoButton'.

Any idea why this is not working?

NOTE - JSFIDDLE AS REQUESTED. :: http://jsfiddle.net/jWFwX/

Upvotes: 0

Views: 236

Answers (1)

guymid
guymid

Reputation: 1206

Parse d into and int first. Working JSFiddle

New code:

function eventButton(d){
    var buttonInt = parseInt(d);
    switch(buttonInt){
    case 0: // STARTBUTTON
        alert("Button");
        break;
    default:
        alert("NoButton");
        alert(d);
    };
};

Upvotes: 1

Related Questions