逻辑在 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);
}
}
相关文章:
- 为什么不't Javascript对我的输入值进行了一些重新检查
- 创建一个类似链接的按钮,并通过Javascript函数打开一个新的弹出窗口
- 将函数的上下文应用于javascript变量
- 使用php或javascript从facebook相册URL中删除多余的部分
- 正在添加'X'按钮,在文本字段旁边使用javascript
- 如何在JavaScript中将字符串转换为函数引用
- 模糊事件的Javascript测试
- Javascript更改图标
- 如何将HTML id分配给元素,以及如何将JavaScript应用于元素
- 如何使用WCF服务和javascript表单post上传.doc文件
- javascript结合了数组和字典
- 这是什么 ==- javascript 运算符
- 从javascript创建一个列表
- 无法在通过jQuery的ajax加载的页面中执行javascript
- Javascript:selenium Web驱动程序isDisplayed()不工作
- 如何通过ajax刷新JSF填充的javascript变量
- 如何在Javascript中将JSon对象转换为数组
- Javascript生成的表单未提交
- 使用javascript将动态表从一个html页面打印到另一个html页
- 通过javascript重定向html传递php变量