1

I apologize if this is a completely stupid question, but I am at the point where the laws of math seem to be bending.

I have a function created within a nested for-loop in Javascript. These are the conditions of the for-loop:

for (var i = 0; i < nRows; i++) {
for (var j = 0; j < nCols; j++) {

Yet, somehow, within this for-loop, I am printing out that nRows = 8, i = 8, nCols = 8, and j = 8, all at the same location (which happens to be within a function I have created that is within the for-loop).

enter image description here

I am assuming I am doing something wrong and that the laws of math have not just disappeared. I was thinking that it might have something to do with the fact that there is a function created within the for-loop, but I am struggling to come up with a feasible way to otherwise implement this.

Here it is as a Fiddle.

Please excuse the fact that this is possibly the lamest Minesweeper implementation to ever exist.

I really really really appreciate any pushes in the correct direction.

Also: the reason I implemented the function within the for-loop is because I was trying to find a way to access the exact button that was clicked. Doing this outside of the for-loop meant that I had to create some type of attributes that would uniquely identify each button to allow me to reference them. I tried doing this by creating HTML attributes for each button ('row' and 'column') but ran into issues because it does not seem that you can save numbers as attributes? Only strings?

Caroline
  • 85
  • 7
  • The easiest solution is to use `let` instead of `var` for the loop variables. The problem is that `i` and `j` continues to exists as their last value after the loop and will be set to their final value when the `mousedown` fires. – Mark Nov 17 '18 at 02:09
  • Oh wow, I had no idea the mousedown interferes with that--thank you!! – Caroline Nov 17 '18 at 02:14
  • This will be a problem with any async function defined like this — not just mousedown. The link Patrick posted says it all better than I can. – Mark Nov 17 '18 at 02:23

0 Answers0