开发者

Recursive function in 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... 
    }            
}

I need execute the function based on the count... the fo开发者_C百科r loop executes perfectly based on the count, but the function executes only once.


You do not have a working termination statement in your function. Start your function with a condition which stops your recursion.

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... 
    }            
}


There are a couple of ways to handle recursive looping (anyone else remember SICP here? Ah... blessed Scheme).

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) 
}

More realistically (and faster), you may want to simply put a while loop inside the function:

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*/ );  
}

If you want to make sure that the function only runs x times, then you could do this:

// 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

       }     
  }
}

Hopefully that can get you started.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜