如何使用更新的变量停止递归和/或重新启动当前函数

时间:2010-12-21 02:17:39

标签: javascript recursion

我有两个基于标准更新自己和彼此的数组(描述的时间比我怀疑的解决方案要长)。

我最终得到的是一个在while循环中调用自身的函数。你可以想象,这导致了一个荒谬的递归量。

这是一个例子(保持简短)

var buildArray=firstFunction(new Array(), existingArray)

function firstFunction(thisArray, existingArray){
     for(test1=0; test1<existingArray.length; test1++){
         if(existingArray[test1][3]=='2'){
           secondFunction(thisArray, existingArray, test1);
        }
     }

function secondFunction(thisArray, existingArray, t1){
       for(test2=0; test2<thisArray.length; test2++){
          if(thisArray[test1]<=existingArray[test2][1] || thisArray[test1]>existingArray[test2[0]){
            // do a bunch of stuff to existingArray, now that existingArray has changed, the whole process needs to start again FROM THE BEGINNING!!!
     return firstFunction(new Array(), existingArray);

              // check that the value isn't already in the 'thisArray'
   var check= new Array(existingArray[test1]);
  else if (jQuery.inArray(check, thisArray==-1){
         // value isn't in the new array, so add it
        thisArray.push(check);
       // thisArray has changed. need to restart the the second function
       secondFunction(thisArray,existingArray);
     }

   }
 }

}
}

我希望

return secondFunction(thisArray, existingArray);

会重置并重启该功能,但显然没有发生。

有没有办法停止当前函数并循环并使用更新的变量重新启动?

2 个答案:

答案 0 :(得分:3)

我没有得到你正在尝试做的事情,但是基于返回停止在secondFunction中执行的事实,并且thisArray永远不会改变, 你可以在firstFunction中添加一个循环:

function firstFunction(thisArray, existingArray){
    var restart = true;
    while(restart)
    {
        restart = false;
         for(test1=0; !restart && test1<existingArray.length; test1++){
             if(existingArray[test1][3]=='2'){
               if(secondFunction(thisArray, existingArray, test1))
               {
                restart = true;
               }
            }
         }
    }

并且在secondFunction中而不是返回数组返回true:

  if(thisArray[test1]<=existingArray[test2][1] || thisArray[test1]>existingArray[test2[0]){
    // do a bunch of stuff to existingArray, now that existingArray has changed, the whole process needs to start again FROM THE BEGINNING!!!
 return true;

答案 1 :(得分:0)

我注意到的一些事情:

    即使您有参数secondFunction()test1中的
  • 即可访问t1
  • secondFunction()的第二次调用不包含最后一个参数
  • secondFunction()的第二次调用即使你在OP中提到它,也没有回复
  • 有一行else if (jQuery.inArray(check, thisArray==-1){,缺少“)”
  • 有一行if(thisArray[test1]<=existingArray[test2][1] || thisArray[test1]>existingArray[test2[0]){缺少“]”
  • for(test1=0; test1<existingArray.length; test1++){中应该是for(var test1...让解析器在递归中知道它自己是一个变量(假设你希望这种情况发生在当然)
  • for(test2=0; test2<thisArray.length; test2++){中应该是for(var test2...让解析器在递归中知道它自己是一个变量(假设你希望这种情况发生在当然)
  • ...

我说你编辑了代码在这里发布。当然没关系,但它让我相信代码的某些部分缺失了。

就丢失的var而言,这可能符合您的利益,但解析器可能会感到困惑。如果没有var,则在文档级别定义变量,而不是在函数级别,也不在最内层范围。我不知道你是否意识到这一点或是否是一个问题。

相关问题