简体   繁体   English

从JavaScript中的二维数组获取列

[英]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 我目前正在尝试与2个玩家进行游戏,并且要检查字段,我需要检查数组的列而不是行

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: 单击一列会发送一个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]);
    }
}

However, this returns the row id instead of the column from id, and I'm not sure how to fix this. 但是,这将返回行ID而不是ID中的列,并且我不确定如何解决此问题。

Your help would be greatly appreciated! 您的帮助将不胜感激!

Thanks in advance 提前致谢

EDIT solution with the help of Gavriel: 在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 field [j,id-1]的意思是:field [x],x其中x是一个表达式: j,id-1 ,该表达式等于id-1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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