逻辑在 javascript 中未正确触发

Logic not firing correctly in javascript

本文关键字:javascript      更新时间:2023-09-26

编辑:我通过将 2d 数组更改为简单数组并使用算术和逻辑来获取坐标来解决问题,请参见下文。

我有一个算法,当坐标有奇偶配对时,将 50 添加到二维数组中(例如 [1][1]、[3][5] 等)。唯一的问题是,它不起作用。根据浏览器控制台,它永远不会触发。这就是它:

if(((col & 1) & row) == 1) { y+= 50; }

我的代码的一个更完整的示例在这里:

//goes through the board's array and calls
//drawChecker to print each found piece
function drawPieces() {
    var row = 0;
    var col= 0;
    for(row = 0; row < 1; row++) {
        var y = row * 100;
        console.log("row " + row + " set x to " + x);
        var flag = (row & 1);
        for(col = 0; col < 8; col++) {
            var x = col*50;
            console.log("column " + col + " set y to " + y);
            console.log("y was " + y);
            if(((col & 1) & row) == 1) { y+= 50; }
            console.log("Now y is " + y);
            console.log("Done setting " + row + "," + col);
            console.log("Final coordinates are " + x + "," + y);
            drawChecker(x,y,square[row][col]);
        }
    }
}

数组是使用以下代码设置的:

var square = new Array(4);
for(i = 0; i < 4; i++) { square[i] = new Array(8); }

您不能仅在第 0 行上测试算法。

function drawPieces() {
    square.forEach(function (a, i) {
        a.forEach(function (b, j) {
            if (i & j & 1) {
                square[i][j] = '#';
            }
        });
    });
}
var square = Array.apply(null, { length: 4 }).map(function () { return Array.apply(null, { length: 8 }).map(function () { return '.'; }); });
drawPieces();
document.write('<pre>'+square.map(function (a) { return a.join(''); }).join(''n')+'</pre>');

因此,我最终将 4x8 的 2d 数组切换到包含 32 个元素的 1d 数组,并将函数更改为:

function drawPieces() {
    for(i = 0; i < 32; i++) {
        var value = square[i];
        var x = (i % 4) * 100; //i%4 gets its column, 0-3
        var y = Math.floor(i / 4) * 50;  //i / 4 gets the row 0-3
        if((i & 4) != 4) { x += 50; } //offset on even-numbered rows
        drawChecker(x,y,value);
        console.log(i + " has coordinates " + x + "," + y);
    }
}