dpvm7231 2013-03-11 14:50
浏览 23
已采纳

外环只发射一次

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?

  • 写回答

3条回答 默认 最新

  • douweihui0178 2013-03-11 14:51
    关注

    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"); 
        };
    };
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作