function replaceNum() { if (count2 < 3) { count4 = 0; }else if(count2 >= 3 && count2 < 6) { count4 = 1; }else if (count2 >= 6 && count2 < 9) { count4 = 2; }else if (count2 >= 9 && count2 < 12) { count4 = 3; }else if (count2 >= 12 && count2 < 15) { count4 = 4; }else if (count2 >= 15 && count2 < 18) { count4 = 5; }else { count4 = 6; } count2 += 1; } 

Is there any way to rewrite this function using a loop?

  • are all variables integer and positive? - Mikhail Vaysman
  • one
    You do not need a cycle but an integer division =) - Duck Learns to Hide
  • In the sense of the whole? - Denisoed
  • in the sense that it is not floating point. - Mikhail Vaysman
  • SchA explain, wait) - Duck Learns to Hide

1 answer 1

In short, according to your logic, you do not need a cycle, and integer division is enough:
Math.floor rounds the result to the nearest smaller integer.

 function replaceNum() { count4 = Math.floor(count2/3); count2 += 1; } 

This code has a number of other stylistic problems, but we'll probably talk about this in the next series)

One of these problems is the naming of variables.
It is not necessary to name the variables count2, count4. Try to call them as meaningfully as possible, it will help when you understand this.

The name of a variable usually consists of one or more English words written in a row. To separate one word from another, each of the following is usually called with a capital letter. This style is called camelCase (camel notation) For example

 myAwesomeVariable = 15; 

Actually, if you change the names of the variables in your code to meaningful ones, it will be like this. Of course, this is ambiguous, you can come up with your beautiful names (in js, by the way, variables in Russian can be called but never, never, never show them to anyone =)); In any case, it will be better than count2, count4

 function processCardIndexes() { cardStackIndex = Math.floor(cardTotalIndex/3); cardTotalIndex += 1; } 
  • Thank! I will try))) - Denisoed
  • "This code has a number of other stylistic problems." Can you briefly describe? - Denisoed
  • @Deniso, so I did not immediately write what to explain for a long time. In short, variable names are bad, and instead of working with function arguments, you work with some top-level variables. Perhaps I can write more or less briefly about naming - Duck Learns to Take Cover
  • Everything comes about experience) I'm still new to this. And thank you very much for the help)))) - Denisoed
  • one
    @DenisoDeniso, this comes with experience. Every counter you have makes sense. Here count2 is the order of the card in the deck, count4 is the order of the card in the current stack. According to this meaning, we must try to name it. It is much easier to write coun2, count4, but it is much more difficult to figure out what they wrote, including to you yourself) - Duck Learns to Hide