2011-07-15 160 views
-1
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循環根據計數完美執行,但函數只執行一次。javascript中的遞歸函數

+0

你的描述有點含糊......你怎麼稱呼那個功能?你是什​​麼意思,它繼續執行?遞歸的含義是一個條件處於活動狀態時函數繼續執行。你退出的情況是什麼?當你調用這個函數時,你的意思是什麼「爭論」?如果繼續傳遞相同的參數,函數將繼續執行... –

+0

如果從內部調用它,則必須在某處停止遞歸的某個條件。否則,它會無休止地自稱。 – RobG

+0

什麼是「obj」參數? ......但大多數情況下,你知道如何使用'this'嗎?如果你想在功能上編程,請調用'DynamicModelView.createModelView(...)'。 –

回答

1

有幾種方法可以處理遞歸循環(任何人都記得SICP在這裏?啊......祝福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) 
} 

更爲現實(快),你可能想簡單地把一個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 

     }  
    } 
} 

希望可以讓你開始。

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

我有嚴重的懷疑,OP甚至知道*爲什麼*他遞歸地調用函數。它只是不加我自己。所以說如何阻止無限遞歸是一回事,但我非常肯定遞歸不是他所需要的。 – Tomalak