Reputation: 17
Hi Guys i hope you can help me.
I have this code which loops through an array with different objects inside and it compares the content of one of the attributes with the content of a given array. Now it works fine, the only problem I have is that it stops after only 1 iteration (this happens with the first loop, not the second one).
Here's the code. I hope you guys can help me.
var checkIfChecked = function () {
for (var i=0; i < recepten.length; i++) {
var kanIkHetMaken = true;
var ditRecept = recepten[i];
for (var i=0; i < ditRecept.nodigeIngredienten.length; i++) {
var dezeIngredienten = ditRecept.nodigeIngredienten[i];
var index = checked.indexOf(dezeIngredienten);
console.log(index);
if (index === -1) {
kanIkHetMaken = false;
return;
}
}
if (kanIkHetMaken === true) {
document.getElementById(ditRecept.id).style.display = "block";
}
console.log('1e recept gedaan');
}};
Upvotes: 0
Views: 4804
Reputation: 386550
Change the variable for the inner loop to j
and take a break
instead of a return
.
for (var j = 0; j < ditRecept.nodigeIngredienten.length; j++) { // change i to j
var dezeIngredienten = ditRecept.nodigeIngredienten[j]; // use j
var index = checked.indexOf(dezeIngredienten);
console.log(index);
if (index === -1) {
kanIkHetMaken = false;
break; // exit the inner loop
}
}
A little improvement with Array#every
:
kanIkHetMaken = ditRecept.nodigeIngredienten.every(function (dezeIngredienten) {
return ~checked.indexOf(dezeIngredienten);
});
Upvotes: 1
Reputation: 451
You are using the same variable i
in the both the loops. So when the inner loop gets over the outer loop checks the updated value of i for comparison.
Use different variable for inner loop like j
Upvotes: 1
Reputation: 3288
Replace return;
with continue;
.
return
terminates the function.
break
terminates the loop.
continue
terminates that iteration and moves on to the next.
Upvotes: 0