Question :
Is there a native way of doing this?
for (var i in vetor) {
for (var j in vetor) {
if (i == j) {
// pula o i
break;
}
}
}
Is there any way to skip i
within the parentheses of the second for?
Answer :
Yes, there is. Just use continue
. In this case, how you want to interact with the outermost loop , you must specify a label for it and use it next to continue
. The label can be specified with an identifier before for
, followed by colon ( :
).
const vetor = [1, 2, 3, 4, 5];
loop_i: for (let i = 0; i < vetor.length; i++) {
loop_j: for (let j = 0; j < vetor.length; j++) {
if (i == j) continue loop_i;
console.log("i:", i, "j:", j);
}
}
Note that in the example the value of j
is only traversed to the current value of i
.
It should be something like this:
for (var i = 0; i < vetor.length; i++) {
for (var j = 0; j < vetor.length; j++) {
if (vetor[i] == vetor[j]) {
i++;
break;
}
}
}
By traversing the vector through the index you have full control of how it is being incremented since it is a variable like any other.