繁体   English   中英

如何使二维数组迭代?

[英]How to make an 2D array to iterate over?

我有一个表,我想通过它获取行和列的坐标,就像它的表有 Row-2 和 col-2

坐标Row = [0,1]Col = [0,1,0,1]

因为我将它存储在一个数组中,所以我想要一种更好的方法将它存储在二维数组中,以便我可以对其进行迭代。考虑如果表有超过 7 行和 cols,那么使用二维数组是否更好?

我写的方法将它存储在数组中,我如何在其中制作一个二维数组?

CTable.prototype.GetTableMapping = function(currentTable)
{
    let oRowCount = currentTable.GetRowsCount();
    let oRowMapping = [];
    let oColumnMapping = [];
    let oTableMapping = [oRowMapping = [], oColumnMapping = []];
    for (let i = 0; i < oRowCount; i++)
    {
        let oRow = currentTable.GetRow(i);
        let oCellCount = oRow.GetCellsCount();
        oRowMapping.push(i);

        for (let j = 0; j < oCellCount; j++)
        {
            let oCell = oRow.GetCell(j);
            oColumnMapping.push(j);
        }
    }
    console.log("Table",oTableMapping);
    console.log("Rows",oRowMapping);
    console.log("Columns",oColumnMapping);
    return oTableMapping[oRowMapping,oColumnMapping];
};

Output:
[
   Row = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
   Cols = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]
]

由于您已经有一个双 for 循环,您可以使用它来创建二维单元格

arr2D[i][j] = oCell;

完整示例(模拟):

 mockTable = { // mocking the portions of your code that i don't know GetRowsCount: () => 11, GetRow: (x) => ({ GetCellsCount: () => 4, GetCell: (x) => x }) } CTable_prototype_GetTableMapping = function(currentTable) { let oRowCount = currentTable.GetRowsCount(); const arr2D = Array(oRowCount); //let oRowMapping = []; //let oColumnMapping = []; //let oTableMapping = [oRowMapping = [], oColumnMapping = []]; for (let i = 0; i < oRowCount; i++) { let oRow = currentTable.GetRow(i); let oCellCount = oRow.GetCellsCount(); arr2D[i] = Array(oCellCount); //oRowMapping.push(i); for (let j = 0; j < oCellCount; j++) { let oCell = oRow.GetCell(j); //oColumnMapping.push(j); arr2D[i][j] = oCell; } } //console.log("Table",oTableMapping); //console.log("Rows",oRowMapping); //console.log("Columns",oColumnMapping); return arr2D; }; const theArray = CTable_prototype_GetTableMapping(mockTable); console.log("cell (1,3)",theArray[1][3]) console.log("full 2D array", theArray)

暂无
暂无

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

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