I would like to know when my for loop will do its last iteration. By this I mean that I only want it to do one action, but for it to be until the end of the loop.
An example would be the following:
for (var i=0; i<accordeon; i++) {
if (UltimaIteracion) {
// Instrucciones de la última iteración
}
}
I am only interested in the final iteration, that is, if there are 5 iterations, only number 5 will activate the if
. The variable accordeon
is of integer type and comes from the DB, therefore it does not always have the same value.
would be something like this
While other answers answer the particular example of your question, to answer the underlying question ( How do I know when the last iteration of my for loop is? ) it's worth remembering how the loop works
for
.loop structure
for
Its general form in JS (and many other languages) is as follows:
(Definitions adapted from the MDN documentation )
Loop Operation
for
Its operation is as follows:
expresión inicial
condición
.3.1 If
condición
evaluated to true, go to step 43.2 If
condición
evaluated to false, go to step 7sentencias a ejecutar
expresión final
for
Graphically, it is equivalent to this flow: see image .
Determining the last iteration of the loop
for
For example, in the following case, in the
expresión final
block we assign a random integer between 1 and 10 to the variablei
.Now that's far from the usual :)
typical case
The most typical use of
for
, which is also the one you use in your example, is the following:i
with an initial value(eg
var i=0
orvar i=valorInicial
)(eg
i<42
ori<accordeon
)(eg
i++
ori=i+1
)i
, but without modifying it.(eg
console.log("Esta es la iteración"+i);
orarreglo[i] = 3*i;
)For this typical case, we know that once the
sentencias a ejecutar
, the variablei
will increase its value by 1. This makes the following ways valid ways to check if we are in the last iteration:It is equivalent to:
Going to your example
It translates to:
Equivalent to
accordeon is an array? Or what kind of variable is it? If it is an array it would be like this:
If it is not an array it would be like this:
As you have been told in other answers, it is as simple as doing
You can do it with a variable of type boolean as you have put in your example, but you will always have to do an if to compare the value of i with your limit, in this case accordeon.
Although the first option seems simpler and more correct.
It's pretty simple, you just have to check that i (the counter for the loop) is equal to the number of items inside the loop.
arreglo