2016-09-17 91 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为什么你可能想避免它,以及如何。