在Javascript中从二维数组中获取列

时间:2016-02-09 13:46:34

标签: javascript arrays

我目前正在尝试与2名玩家进行游戏,为了检查字段,我需要检查数组的列而不是行

这是我目前的代码:

    /*    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

单击列会发送1-8(8列)中的数字,这将进入以下功能:

function doeZet(id) {

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

但是,这会从id返回行id而不是列,我不知道如何解决这个问题。

非常感谢您的帮助!

提前致谢

在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
            }


    }
}

1 个答案:

答案 0 :(得分:2)

而不是:

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

你需要:

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

field [j,id-1]表示:field [x],xhere x是表达式:j,id-1,该表达式等于id-1

相关问题