I have what (to me) looks like a pretty basic nested loop. Except the outer loop is only firing the first time:
var js_recipes = <?php echo json_encode($recipesArray); ?>;
console.log("there are " + js_recipes.length + " recipes"); //console confirms 2
for (var i = 0; i < js_recipes.length; i++) {
console.log("adding recipe"); //only fires once
js_recipe = js_recipes[i];
//add each ingredient
for (var i = 0; i < js_recipe.ingredients.length; i++) {
console.log("adding ing"); //fires multiple times for first recipe
};
};
console.log("looping complete");//fires ok
The console output is:
There are 2 recipes
adding recipe
adding ing
adding ing
adding ing
adding ing
looping complete
I must be missing something simple, but why am I only iterating over the first recipe?
The scope of a variable is either the global scope or the function where it is declared, so you have only one i
in this code and i
is incremented by the inner loop as well as the outer loop.
Use different iterator variables for the different loops.
for (var i = 0; i < js_recipes.length; i++) {
console.log("adding recipe");
js_recipe = js_recipes[i];
//add each ingredient
for (var j = 0; j < js_recipe.ingredients.length; j++) {
console.log("adding ing");
};
};
You're using the same variable i
. Because of variable hoisting, both of those declarations become one. Thus i
get's incremented twice on each pass ...
Might try setting the inner for loop to be a different variable than i, such as j, in the event there is a function variable scope issue.