2016-09-17 95 views
1

我想知道JavaScript中的continue語句的結構化等價物是什麼?我試圖擺脫繼續的聲明,但不知道如何。任何人都可以將我指向正確的方向嗎?謝謝!JavaScript中continue語句的等效代碼

function Hand() { 
    this.cards = new Array(); 

    this.addOneCard = function(card) { 
     this.cards.push(card); 
    } 

    this.evaluateHand = function(){ 
     // Needs to handle two aces better 
     var total1 = new Number; 
     var total2 = new Number; 

     for(var i in this.cards) { 
      if (this.cards[i].value == "A") { 
       total1 += 1; 
       total2 += 11; 
       continue; 
      } 
      if (isNaN(this.cards[i].value * 1)) { 
       total1 += 10; 
       total2 += 10; 
       continue; 
      } 
      total1 += Number(this.cards[i].value); 
      total2 += Number(this.cards[i].value); 
     } 
     return [total1, total2]; 
    }; 
} 
+1

你爲什麼需要改變? 「繼續」是語言的一部分,非常適合您的需求。 –

回答

1

else if對將幫助你在這裏:

for(var i in this.cards) { 
     if (this.cards[i].value == "A") { 
      total1 += 1; 
      total2 += 11; 
     } 
     else if (isNaN(this.cards[i].value * 1)) { 
      total1 += 10; 
      total2 += 10; 
     } 
     else { 
      total1 += Number(this.cards[i].value); 
      total2 += Number(this.cards[i].value); 
     } 
    } 
-2

一種選擇是:

this.cards.forEach(function(card) { 
    if (card.value == "A") { 
     total1 += 1; 
     total2 += 11; 
     return; 
    } 
    if (isNaN(card.value * 1)) { 
     total1 += 10; 
     total2 += 10; 
     return; 
    } 
    total1 += Number(card.value); 
    total2 += Number(card.value); 
}); 

顯然,有些人認爲return終止一切...... return停止當前運行的功能元素,使得下一次迭代立即開始,就像continue一樣。我並不是說這是比使用continue更好的選擇,但它絕對是一種選擇。

+0

'return'結束函數,但繼續執行for循環。 –

+0

'returns'結束循環中的函數並開始循環的下一次迭代。 「繼續」在做什麼? – Guig

+0

否,'return'終止函數(和)。沒有更多的迭代。 'continue'跳轉到for循環的開頭,並跳轉到for循環的結尾。 –

0

這應該適用於任何語言的真實,而不僅僅是Java腳本

function Hand() { 
    this.cards = new Array(); 

    this.addOneCard = function(card) { 
     this.cards.push(card); 
    } 

    this.evaluateHand = function(){ 
     // Needs to handle two aces better 
     var total1 = new Number; 
     var total2 = new Number; 

     for(var i in this.cards) { 
      if (this.cards[i].value == "A") { 
       total1 += 1; 
       total2 += 11; 
      } 
      else if (isNaN(this.cards[i].value * 1)) { 
       total1 += 10; 
       total2 += 10; 
      } 
      else { 
       total1 += Number(this.cards[i].value); 
       total2 += Number(this.cards[i].value); 
      } 
     } 
     return [total1, total2]; 
    }; 
} 
2

continue語句在JavaScript中有效。您可以像使用任何語言一樣使用它。

之後說,你可以閱讀這interesting discussion爲什麼你可能想避免它,以及如何。