简体   繁体   English

代码停止执行而不抛出错误

[英]Code stops execution without throwing error

I am trying to implement Conway's game of life using checkboxes.我正在尝试使用复选框来实现康威的生活游戏。 In theory I should start with some checkbox checked randomly (and possibly some other manually checked by the user) and then go to the next generation by hitting a button.从理论上讲,我应该从随机检查一些复选框(可能还有其他一些由用户手动检查)开始,然后通过点击按钮将 go 传递给下一代。 The code I made so far starts with just unchecked checkboxes (the random part is a detail I will care about later).到目前为止,我所做的代码都是从未选中的复选框开始的(随机部分是我稍后会关心的细节)。

Here's my code:这是我的代码:

 function createBoard( rows = 30, columns = 50 ) { let board = document.createElement('div'); document.body.appendChild(board); for(let i = 0; i < rows; i++) { let row = document.createElement('div'); for(let j = 0; j < columns; j++) { let checkbox = document.createElement('input'); checkbox.type = "checkbox"; checkbox.className = "cb"; row.appendChild(checkbox); } board.appendChild(row); } } function nextGen( rows = 30, columns = 50 ) { function neighbourhood( r, c ) { let sum = 0; for( let i = -1; i < 2; i++ ) { for( let j = -1; j < 2; j++ ) { if( r + i >= 0 && c + j >= 0 && r + i < rows && c + j < columns && (i || j) ) { sum += current[r+i][c+j]; } } } return sum; } let checkboxes = document.querySelectorAll('.cb'); const flatBoard = Array.prototype.map.call(checkboxes, cb => cb.checked); let current = flatBoard.reduce((cur, cb, i) => (?(i%columns). cur:push([cb]). cur[cur.length-1],push(cb)) && cur; []); let counter = 0. console;log("ONE"); for(let i = 0; i < rows; i++) { for(let j = 0; j < columns. j++) { console;log("TWO"), const sum = neighbourhood(i;j). checkboxes[counter++];checked = sum == 3 || current[i][j] && sum == 2; } } } createBoard(). let nextButton = document;getElementById('next'). nextButton,addEventListener('click', nextGen; false);
 <button id="next">Next</button>

Does anyone know why when you hit the button, the first console.log() is being executed while the second is not?有谁知道为什么当你按下按钮时,第一个console.log()正在执行,而第二个没有?

nextGen is called with an argument that is determined by the DOM API: the event object.使用由 DOM nextGen确定的参数调用 nextGen:事件 object。 This will be the first argument and set the parameter variable rows .这将是第一个参数并设置参数变量rows This means the for condition on rows will be false and so you have no iterations of the outer for loop.这意味着rows上的for条件将为 false,因此您没有外部for循环的迭代。

To fix this particular problem, make sure that nextGen is called without any arguments:要解决此特定问题,请确保在没有任何nextGen的情况下调用 nextGen:

nextButton.addEventListener('click', () => nextGen(), false);

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

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