I would like to know how I can make my loop change when the count of a value is a multiple of 5 or whatever multiple I want.
This is my code:
var multiplo = ["aguacate ","albaricoque ","ananá","arándano","arándano ","banana","cereza ","ciruela","higo","kiwi","lima","limón","mandarina","mango","manzana","maracuyá","melocotón ","melón","membrillo",];
var cont = 0;
var valorc = "";
var limite = 5;
function parar() {
var e = setInterval( function() {
switch(cont) {
case 1:
valorc = multiplo[0];
break;
case limite * 1:
valorc = multiplo[1];
break;
case limite * 2:
valorc = multiplo[2];
break;
case limite * 3:
valorc = multiplo[3];
break;
case limite * 4:
valorc = multiplo[4];
break;
case limite * 5:
valorc = multiplo[5];
break;
}
cont++;
console.log(cont)
console.log(valorc)
if (cont === 100) {
clearInterval(e);
}
}, 300);
}
parar();
That code does it perfectly, my problem is that I have to write a lot of code in case I want more than 100. In case I want a count of 1000 I don't want to write all that code.
I have tried using a switch
:
switch(cont) {
case 1:
valorc = multiplo[0];
break;
case limite * 1:
valorc = multiplo[1];
break;
case limite * 2:
valorc = multiplo[2];
break;
case limite * 3:
valorc = multiplo[3];
break;
case limite * 4:
valorc = multiplo[4];
break;
case limite * 5:
valorc = multiplo[5];
break;
I would like to know if there is a way that can be done, I tried this way but I always get the last value.
for( var i=cont;i<multiplo.length; i++ ) {
switch(cont) {
case 1:
valorc = multiplo[i];
break;
case limite * 1:
valorc = multiplo[i];
break;
case limite * 2:
valorc = multiplo[i];
break;
case limite * 3:
valorc = multiplo[i];
break;
case limite * 4:
valorc = multiplo[i];
break;
case limite * 5:
valorc = multiplo[i];
break;
}}
And this other:
for( var i=cont;i<multiplo.length; i++ ) {
switch(cont) {
case limite * cont:
valorc = multiplo[i];
break;
}}
I would like to know if anyone has any idea how to make it work without writing so much code to save time and such. I am open to any solution.
Use the modulo operator to simplify your code. In JavaScript the modulus operator is
%
and what it does is return the remainder of the integer division of the operators. For example,23 % 5 = 3
and25 % 5 = 0
.So in your code what you could do is something like this:
Each time the result of the module with 5 is 0 (that is, each time it is a multiple of 5), change the value of the variable you want.