Victor Le
Victor Le

Reputation: 1788

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?

Upvotes: 3

Views: 146

Answers (2)

Gerardo Furtado
Gerardo Furtado

Reputation: 102194

Using a ternary operator:

for(i = 1; i < 101 ; i++){
    var color = ((i%10 != 0 && i%10 <= 5) && i<51) ? "red" 
    : ((i%10 === 0 || i%10 > 5) && i<51) ? "green" 
    :((i%10 != 0 && i%10 <= 5) && i>=51) ? "blue" 
    : "pink";
    console.log(i + " - " + color)
}

As SO snippet doesn't console.log all 100 values, here is a JSfiddle: https://jsfiddle.net/jcky4dkp/1/

What does this code do?

The first condition checks if the last digit of the number is less than 6 and if the number itself is less than 51:

(i%10 != 0 && i%10 <= 5) && i<51

If that's true you'll have "red", otherwise it will check the second condition, if the last digit of the number is greater than 5 and if the number itself is less than 51:

(i%10 === 0 || i%10 > 5) && i<51

If that's true you'll have "green", otherwise it will check the third condition, if the last digit of the number is less than 6 and if the number itself is greater than 51:

(i%10 != 0 && i%10 <= 5) && i>51

If that's true you'll have "blue", otherwise, it will return "pink"

Upvotes: 1

Cristian Lupascu
Cristian Lupascu

Reputation: 40546

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>

Upvotes: 2

Related Questions