javascript中的递归函数

时间:2011-07-15 11:32:32

标签: javascript

var DynamicModelView = {          
    createModelView: function (obj,vitalslength,headerValue) {     
      for(vitalsCount = 0, vitalsLen = vitalslength; vitalsCount < vitalsLen; vitalsCount++) {
              // Business logic... with obj and headerValue

       }       

      I need to call this function again.    
      When i call `this.createModelView(arguements)` it keeps on executing... 
    }            
}

我需要根据计数执行函数... for循环基于计数完美执行,但该函数只执行一次。

2 个答案:

答案 0 :(得分:2)

您的函数中没有工作终止语句。使用阻止递归的条件启动函数。

var DynamicModelView = {          
    createModelView: function (obj,vitalslength,headerValue) {     

       ***if (<stop condition>) return;***

       for(vitalsCount = 0, vitalsLen = vitalslength; vitalsCount < vitalsLen; vitalsCount++) {
              // Business logic... with obj and headerValue

       }       

      I need to call this function again.    
      When i call `this.createModelView(arguements)` it keeps on executing... 
    }            
}

答案 1 :(得分:1)

有几种方法可以处理递归循环(其他人还记得SICP吗?啊......祝福方案)。

createModelView: function (obj,vitalslength,headerValue) {     
  for(vitalsCount = 0, vitalsLen = vitalslength; 
          vitalsCount < vitalsLen; vitalsCount++) {
          // Business logic... with obj and headerValue

   }       

  // the following will force this method to keep going with the same parameters
  // unless you put a conditional return statement before it
  // I always use an interim variable so JS can't get confused.
  var args = arguments; 
  // are you sure it's this here and not DynamicModelView.createModelView
  this.createModelView.apply(this, args) 
}

更逼真(更快),您可能只想在函数中放置一个while循环:

createModelView: function (obj,vitalslength,headerValue) {     
  do {
      for(vitalsCount = 0, vitalsLen = vitalslength; 
             vitalsCount < vitalsLen; vitalsCount++) {
             // Business logic... with obj and headerValue

       }     
  } while( /* condition which needs to be met to finish loop*/ );  
}

如果你想确保该函数只运行x次,那么你可以这样做:

// notice the last parameter?
createModelView: function (obj,vitalslength,headerValue, x) {  
  for( var i = 0; i < x; i++ )   
  {
      for(vitalsCount = 0, vitalsLen = vitalslength; 
             vitalsCount < vitalsLen; vitalsCount++) {
             // Business logic... with obj and headerValue

       }     
  }
}

希望这可以帮助你开始。