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:
however if i change the sequence to i === 8 * increment
, the output is:
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:
3
Answers
The correct check for end of line is
as there are 8 cells in a line, you need to start a new line every 8th cell, which will have indexes (given 0-based indexing) of 7, 15, 23 etc. i.e.
i % 8 == 7
You can also simplify your code somewhat:
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 expressioni % 8 === 7
will be true at the 8th, 16th, 24th, … square.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:
This will work with any size board. Demo: