编辑以包含有关我尝试实现的更多信息。
下面的代码运行正常,但是当我取消注释boardGen:..
和board:..
部分以使board
具有灵活的大小时,不会创建任何板,或者它是0尺寸(无误差)。有人可以解释原因,并告诉我如何使其正常工作?
$(document).ready(function () {
var app = {
// define inital matrix
// to do: build helper function to make arbitary size grid
board : [[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]],
// boardGen : function (rows, cols) {
// var array = [],
// row = [];
// while (cols--)
// row.push(0);
// while (rows--)
// array.push(row.slice());
// return array;
// },
// board : function () {
// return app.boardGen(6, 6);
// },
init : function () {
// on startup
app.createCells();
app.main();
},
createCells : function () {
// create cells and populate
var html = '<table>';
for (var i = 0, len = app.board.length; i < len; ++i) {
html += '<tr>';
for (var j = 0, rowLen = app.board[i].length; j < rowLen; ++j) {
html += `<td class="cell" data-gridpos="[${i}, ${j}]">`;
html += `${app.board[i][j]}</td>`;
}
html += "</tr>";
}
html += '</table>';
$('#instructions').after(html);
},
numNeighbours : function (arr, coords) {
var row = coords[0];
var col = coords[1];
var neighbours = 8;
var offsets = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]];
for (offset of offsets) {
// prevent errors for non-existant indices
try {
neighbour = arr[row + offset[0]][col + offset[1]];
} catch (err) {
neighbour = undefined;
}
if (!neighbour) {
neighbours--;
}
}
return neighbours;
},
main : function () {
var coords = [];
$(document).on('click', '.cell', function () {
// get data for current cell
coords = $(this).data('gridpos');
// highlight current cell
$(this).css('background-color', 'lightgray');
$('td').not(this).css('background-color', '');
// update info re neighbours
$('#info').html('Touching: ' + app.numNeighbours(app.board, coords));
// console.log(app.numNeighbours(coords));
// toggle values in cells and update board
if (app.board[coords[0]][coords[1]] == 1) {
app.board[coords[0]][coords[1]] = 0;
$(this).html('0')
} else {
app.board[coords[0]][coords[1]] = 1;
$(this).html('1')
}
});
}
};
app.init();
});
答案 0 :(得分:1)
app
在步骤1中,您无法读取app
的值,因为在步骤3之前它没有值。