-1

你能帮我调试这段代码吗?我看不到其中的错误。也没有输出来确定错误。

 function go()
{
    var procedures = [];

    for (var i = 0; i < 10; i++) 
    {
        procedures[procedures.length] = function () 
        {
            alert("You are now " + i + " years old");
        } 
        run_procs(procedures);
    }

    function run_procs(procs) 
    {
        for (var i = 0; i < procs.length; i++)
        {
            procs[i]();
        }
    }

    go();
}
4

4 回答 4

2

您已经在函数内部执行了函数。放在go();外面。

于 2013-05-20T08:08:43.237 回答
1

为方便起见,我已在线评论了您遇到的一些问题。

 function go()
 {
 var procedures = [];

 for (var i = 0; i < 10; i++) 
 {
     procedures[procedures.length] = function () 
     {
         alert("You are now " + i + " years old");
         //this function doesn't return anything, so you will never assign any values to procedures[procedures.length]
     } 
     run_procs(procedures);
 }

 function run_procs(procs) 
 {
     for (var i = 0; i < procs.length; i++)
     {
         procs[i]();
         //the argument you have passed to this function is not a function itself, so this won't do much.
     }
 }
 //this is inside the go() declaration so you aren't actually calling it. 
 go();
 }

这些代码都不会运行,因为您只是声明了该函数而实际上并未调用它。因此,您不会收到任何错误。

于 2013-05-20T08:16:21.630 回答
0
  1. 您一次又一次地在数组中加载相同的点。
  2. 你打电话给procs?什么是过程?
  3. 去是里面去吗?

尝试以下修复:

var procedures = [];
function go()
{
   for (var i = 0; i < 10; i++) 
   {
       procedures[i] = function () 
       {
           alert("You are now " + i + " years old");
       }
       run_procs();
   }


}

function run_procs(procs)
{
    for (var i = 0; i < procedures.length; i++)
     {
         procedures[i]();
     }
 }

 go();

jsFiddle 示例http://jsfiddle.net/n8FSe/

于 2013-05-20T08:08:03.197 回答
0

您正在调用go内部函数go以创建无限递归。您需要go从函数外部调用该函数才能开始执行该函数。

function go()
{
    var procedures = [];

    for (var i = 0; i < 10; i++) 
    {
        procedures[procedures.length] = function () 
        {
            console.log("You are now " + i + " years old");
        } 
        run_procs(procedures);
    }

    function run_procs(procs) 
    {
        for (var i = 0; i < procs.length; i++)
        {
            procs[i]();
        }
    }

}

go(); // <<-- this should be outside the function body
于 2013-05-20T08:11:32.730 回答