我有一个(对我来说)看起来非常基本的嵌套循环。除了外循环仅在第一次触发之外:
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
控制台输出为:
There are 2 recipes
adding recipe
adding ing
adding ing
adding ing
adding ing
looping complete
我一定错过了一些简单的东西,但为什么我只迭代第一个菜谱?
最佳答案
变量的范围是either the global scope or the function where it is declared ,因此这段代码中只有一个 i
,并且 i
通过内循环和外循环递增。
对不同的循环使用不同的迭代器变量。
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");
};
};
关于php - 外循环只触发一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15341574/