简体   繁体   中英

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. 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?

nextGen is called with an argument that is determined by the DOM API: the event object. This will be the first argument and set the parameter variable rows . This means the for condition on rows will be false and so you have no iterations of the outer for loop.

To fix this particular problem, make sure that nextGen is called without any arguments:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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