Viet Le Viet Le - 1 month ago 16
Javascript Question

Forloop confusion

Hey everyone I'm having problem trying to set up this forloop..but I'm failing

If you look at this picture here

I need to make those little dots be the same color as the big number depending on which section they are in.

I'm adding elements onto the front page through a for loop

for(i = 1; i < 100 ; i++){

console.log("Number " + i + " with the color red")

}


So for example 1-5, 11-15, 21-25, 31-35, 41,45 would be red

Would I need to use regex?

Answer

You can use the following function that takes as input an integer between 0 and 99 and outputs the section number (1 to 4):

((n % 10 > 4) ? 1 : 2) + ((n > 49) ? 2 : 0)

The final result is made of two parts:

  • ((n % 10 > 4) ? 1 : 2) - this part checks whether the number ends in either 0-4 or 5-9. In the former case, output 1. In the latter, output 2.
  • ((n > 49) ? 2 : 0) - add 2 to the final result if n is 50 or above (to distinguish between sections 1,2 and sections 3,4).

This formula is implemented in the getSectionNumber(n) function in the demo below:

var table = document.querySelector('table tbody');

// n is a number between 0 and 99
// output is a section (1 - 4)
function getSectionNumber(n) {
  return ((n % 10 > 4) ? 1 : 2) + ((n > 49) ? 2 : 0);
}

var sectionColors = {
  1: 'darkred',
  2: 'darkblue',
  3: 'darkgreen',
  4: 'yellow'
};

for(var i = 0; i < 10; i++) {
  var row = document.createElement('tr');
  table.appendChild(row);
  for(var j = 0; j < 10; j++) {
    var cell = document.createElement('td');
    var cellId = i*10 + j
    cell.textContent = cellId;
    cell.style.backgroundColor = sectionColors[getSectionNumber(cellId)];
    row.appendChild(cell);
  }
}
<table>
  <tbody>
  </tbody>
</table>