简体   繁体   中英

Getting column from two dimensional array in Javascript

I'm currently trying to make a game with 2 players and in order to check the field I need to check the columns of the array instead of the rows

This is the code I currently have:

    /*    Array containing the playing field 8 x 8 

       C0 C1 C2 C3 C4 C5 C6 C7
    R0[0][0][0][0][0][0][0][0]
    R1[0][0][0][0][0][0][0][0]
    R2[0][0][0][0][0][0][0][0] 
    R3[0][0][0][0][0][0][0][0] 
    R4[0][0][0][0][0][0][0][0]
    R5[0][0][0][0][0][0][0][0] 
    R6[0][0][0][0][0][0][0][0] 
    R7[0][0][0][0][0][0][0][0]
*/

var row0 = [1,2,3,4,5,6,7,8],
    row1 = [0,0,0,0,0,0,0,0],
    row2 = [0,0,0,0,0,0,0,0],
    row3 = [0,0,0,0,0,0,0,0],
    row4 = [0,0,0,0,0,0,0,0],
    row5 = [0,0,0,0,0,0,0,0],
    row6 = [0,0,0,0,0,0,0,0],
    row7 = [0,0,0,0,0,0,0,0];

var field = [row0,row1,row2,row3,row4,row5,row6,row7];
console.log(field[0][0]); // Get the first item in the array

Clicking on a column sends a number from 1-8 (8 columns), this goes into the following function:

function doeZet(id) {

    // check alle cellen van 8 -> 0
    for (j=7; j>=0; j--) {
        console.log(id)
        console.log(field[j,id-1]);
    }
}

However, this returns the row id instead of the column from id, and I'm not sure how to fix this.

Your help would be greatly appreciated!

Thanks in advance

EDIT solution with the help of Gavriel:

    function doeZet(id) {

    // check alle cellen van 8 -> 0
    for (j=7; j>=0; j--) {

        if(field[j][id-1] == 0)
            {
                field[j][id-1] = 1
                console.log(j)
                return j
            }


    }
}

Instead of:

console.log(field[j,id-1]);

You need:

console.log(field[j][id-1]);

field[j,id-1] means: field[x], xhere x is an expression: j,id-1 , and that expression equals to id-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