Can anyone take a look at this Javascript code and see if there is an opportunity for simplifying. The code runs and generates a chess board by adding a dark color class or light to each cell in the board.
function colours()
{
var rows = document.querySelectorAll(".row");
for (var i = 1; i <= 8; i++)
{
var currRow = rows[i];
var cells = currRow.querySelectorAll(".cell");
if(i%2==0)
{
for (var j = 1; j < cells.length; j++)
{ var currCell = cells[j];
if(j%2==0)
currCell.classList.add("dark");
else
currCell.classList.add("light");
}
}
else
for (var j = 1; j < cells.length; j++)
{
var currCell = cells[j];
if(j%2==0)
currCell.classList.add("light");
else
currCell.classList.add("dark");
}
}
}
-
1\$\begingroup\$ Can you provide the html and css you are using ? Possibly setting up a live snippet on the question. \$\endgroup\$Isac– Isac2018年03月22日 23:23:08 +00:00Commented Mar 22, 2018 at 23:23
2 Answers 2
Zero indexed array and clean code.
The for
loops are a little strange starting at 1. Normally you index into an array from 0. If you have 8 items in the array the loop would be for(i = 0; i < array.length; i ++){
but you may have extra elements on the array. Without the HTML I can only guess.
For finding the checker colour you can add the x and y (i + j) % 2
and then get the remainder of 2 saving you the second loop.
Function names should tell you what they do. You have colours
which could mean anything.
The whole thing can be done as follows
function createCheckerBoard() {
const rows = document.querySelectorAll(".row");
for (let i = 0; i < 8; i++) {
var cells = rows[i].querySelectorAll(".cell");
for (let j = 0; j < cells.length; j++) {
cells[j].classList.add((j + i) % 2 ? "light": "dark");
}
}
}
Using const
for variables that do not change and a ternary operator for the class selection.
The most important part of coding is good and consistent style. Having messy code makes it harder to read and near impossible sometimes to spot subtle syntax bugs. Many IDE's can format the code for you, learn to use them they will save you many hours of bug hunting frustration.
You can reduce the complex if statement and the resulting duplication by checking if i+j
is even or odd to color a place. i.e.
function colours() {
var rows = document.querySelectorAll(".row");
for (var i = 1; i <= 8; i++) {
var currRow = rows[i];
var cells = currRow.querySelectorAll(".cell");
for (var j = 1; j <= 8; j++) {
var color = (i+j) % 2==0 ? "light" : "dark";
currCell.classList.add("dark");
var currCell = cells[j];
}
}
}