Sunday 15 July 2012

javascript - Cannot read property '1' of undefined error -



javascript - Cannot read property '1' of undefined error -

i've checked questions similar mine , tried knew. bug driving me crazy.

i doing "game" consists on nxn tables numbers 1-8 , number 0 (this numbers represented image files, , number 0 transparent image). purpouse of game numbers in order. link brief thought of talking --> game.

so when click number 2 (in example) should go downwards , transparent image should go (changing src).

this code:

<script language="javascript"> const n=3; var atabla= creartabla(n); document.write("<table>"); (f=0;f<n;f++){ document.write("<tr>"); (c=0;c<n;c++){ document.write("<td>"); document.write('<img src = "numbers2/n'+atabla[f][c]+'.gif" id="im'+f+c+'" onclick="mover('+f+','+c+');tiempo()" >'); document.write("</td>"); } document.write("</tr>"); } document.write("</table>"); function mover(f,c){ //derecha if(atabla[f][c+1] == 0){ aaux = atabla[f][c+1]; atabla[f][c+1] = atabla[f][c]; atabla[f][c] = aaux; aux = document.images["im"+f+(c+1)].src; document.images["im"+f+(c+1)].src = document.images["im"+f+c].src; document.images["im"+f+c].src = aux; }//izquierda if(atabla[f][c-1] == 0){ aaux = atabla[f][c-1]; atabla[f][c-1] = atabla[f][c]; atabla[f][c] = aaux; aux = document.images["im"+f+(c-1)].src; document.images["im"+f+(c-1)].src = document.images["im"+f+c].src; document.images["im"+f+c].src = aux; } //arriba if(atabla[f-1][c] == 0 && atabla[f-1][c] != 'undefined'){ aaux = atabla[f-1][c]; atabla[f-1][c] = atabla[f][c]; atabla[f][c] = aaux; aux = document.images["im"+(f-1)+c].src; document.images["im"+(f-1)+c].src = document.images["im"+f+c].src; document.images["im"+f+c].src = aux; } //abajo if(atabla[f+1][c] == 0 && atabla[f+1][c] != 'undefined'){ aaux = atabla[f+1][c]; atabla[f+1][c] = atabla[f][c]; atabla[f][c] = aaux; aux = document.images["im"+(f+1)+c].src; document.images["im"+(f+1)+c].src = document.images["im"+f+c].src; document.images["im"+f+c].src = aux; } }

function creartabla(n) done function works perfecty. homecoming 2d array. , parameter utilize nxn in case creates 3x3 table.

the games works when move numbers left, right , up, when move numbers downwards if case in line 2 , 3 ( f == 0 , f == 1 in array positions). when seek move , element on first line (number 2 in link provided) gives error: uncaught typeerror: cannot read property '2' of undefined

what can prepare that? new javascript.

what need check accessing valid location, both row , column between 0 , 2. in function can assume (f, c) valid location in board. things (f-1, c) might not valid location. so, need check them:

if(c+1 <= 2 && atabla[f][c+1] == 0){... if(c-1 >= 0 && atabla[f][c-1] == 0){... if(f-1 >= 0 && atabla[f-1][c] == 0){... if(f+1 <= 2 && atabla[f+1][c] == 0){...

if first status false, the sec status not evaluated, preventing typeerror in current code.

javascript html5

No comments:

Post a Comment