Cậu Long
Cậu Long

Reputation: 11

Can someone explain why this happen?

const chessBoard = document.querySelector("#board");
let aSwitch = true; // define a switch to create black & white square
let increment = 1; // will be use to determine the row of the board

for (let i = 0; i < 64; i++) {
  let square = document.createElement("div");
  square.classList.add("square");

  if (aSwitch === true) {
    square.classList.add("white");
    aSwitch = false;
   } else {
        square.classList.add("black");
    aSwitch = true;
  }

  if (i === 7 * increment) {
    increment++;
   aSwitch = !aSwitch;
  } // ensure that the next row will follow a checkered pattern
  chessBoard.append(square);
}

output:

chessboard with the equation 8 * increment - 1

however if i change the sequence to i === 8 * increment, the output is:

chessboard with the equation 8 * increment

Please help me understand this phenomenon since i am very dummb and confused, thanks alot!

I did try using the internet, and best i came up with was that the square was in a 0-index sequence, but when i try using the equation 7 * increment, the output was also wrong:

chessboard with equation 7 * increment

Upvotes: 0

Views: 91

Answers (2)

blex
blex

Reputation: 25659

Another way of solving it is by nesting loops. An outer one for rows, and an inner one for columns. You can then use this formula to get the remainder (%) of a division by 2 to determine if the sum is even or odd:

(col + row) % 2

This will work with any size board. Demo:

const chessBoard = document.querySelector("#board");
const boardSize = 8;
// Set the width of the board accordingly
document.querySelector(':root').style.setProperty('--boardsize', boardSize);

for (let row = 0; row < boardSize; row++) {
  for (let col = 0; col < boardSize; col++) {
    const color = (col + row) % 2 ? 'black' : 'white';
    addSquare(color);
  }
}

function addSquare(color) {
  const square = document.createElement("div");
  square.classList.add("square", color);
  chessBoard.append(square);
}
<div id="board"></div>                                                                                                       <style>:root{--boardsize: 8}#board{width:calc(var(--boardsize) * 20px);border:1px solid #000;line-height:0}.square{width:20px;height:20px;display:inline-block}.black{background:#000}</style>

Upvotes: 1

gimix
gimix

Reputation: 3833

Your approach is not correct:

7 * increment will give 7, 14, 21, ... So you are checking the 8th square, but then the 15th, the 22nd and so on.

8 * increment will give 8, 16, 24, ... Again. this is not what you want.

You need to use the remainder operator %: the expression i % 8 === 7 will be true at the 8th, 16th, 24th, ... square.

Upvotes: 0

Related Questions