简体   繁体   中英

Uncaught TypeError: Cannot read property '1' of undefined in array

var grid = [];
    for (var i = 0;i < 6;i++)
    {
        for (var j = 0; j < 6; j++)
        grid[i] = [];
    }

    //Checking function(how many bombs near)
    function check(cx,cy)
    {
        var numb = 0;
        if (grid[cx][cy - 1] == "B") numb++;
        if (grid[cx][cy + 1] == "B") numb++;
        if (grid[cx - 1][cy] == "B") numb++;
        if (grid[cx + 1][cy] == "B") numb++;
        if (grid[cx - 1][cy - 1] == "B") numb++;
        if (grid[cx + 1][cy - 1] == "B") numb++;
        if (grid[cx - 1][cy + 1] == "B") numb++;
        if (grid[cx + 1][cy + 1] == "B") numb++;

        return numb;
    }** 

it gives me an error when i try to check every position that contains cx + or - 1, i tried to make the array in other ways but it didn't help. I try to make a minesweeper game, so here i check how many bombs are near each given idex

To prevent using indices of an array which have no array or value, you could use a function and hand over the array and indices and return true , if the value is 'B' , otherwise false .

The check takes plase with in operator and a guard operator ( logical AND && ) which breaks on false and continues for true and checks then the value.

function checkB(array, i, j) {
    return i in array && array[i][j] === 'B';
}

// call
if (checkB(grid, cx, cy - 1)) numb++;

check your function

when call check(0,0)

if (grid[cx][cy - 1] == "B") numb++;

grid[0][0-1]=

0-1=?!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM