while循环给出了奇怪的结果

时间:2017-01-05 12:20:51

标签: javascript if-statement while-loop

这个while循环有时会起作用,有时它不起作用。谁能明白为什么? 我觉得它应该开始循环,并保持循环直到经销商总数大于17并且击中了其他区块。一旦进入else块,它应该更新结果值。但是,有时它会跳转到else块然后直接跳到console.log(outcome)并告诉我它是未定义的。有时它会返回正确的结果。例如它输出经销商的胜利!' 我觉得我遇到了各种情况? 我甚至放入console.logs并且行dealersTotal = total得到正确更新。为什么不连续循环?

 dealerTwisted = () => {
    let dealersTotal = this.state.dealersOverallTotal;
    let playersTotal = this.state.playersOverallTotal;
    let looping = true;
    let outcome = '';
    while(looping){
      if(dealersTotal < 17){
        this.deal2Dealer();
        let dealersDeck = this.state.dealersDeck;
        let newDealersDeckTotal = [];
        for (var i=0; i < dealersDeck.length; i++){
          newDealersDeckTotal.push(dealersDeck[i].rankValue)
        }
        let total = newDealersDeckTotal.reduce(function(a, b) {
          return a + b;
        },
        0);
        dealersTotal = total;
      }
      else {
        if(dealersTotal > 21){
          outcome = 'player wins!';
          break;
        }
        else if(playersTotal > dealersTotal){
          outcome = 'player wins!'; 
          break;
        }
        else if (playersTotal == dealersTotal){
          outcome = 'tie!';
          break;
        }
        else if (dealersTotal > playersTotal){
          outcome = 'dealer wins!';
          break;
        }
        else {
          console.log('got here');
          break;
        }
      }
      console.log(outcome);
      this.setState({resultOutcome: outcome})
      break;
    }
  };
编辑:想想我已经弄明白了。它必须进入第一个,如果它然后它击中大其他结束时的休息。但是,问题仍然是我需要它循环,只有在所有条件都被覆盖后才会中断。溶液

1 个答案:

答案 0 :(得分:0)

你是否在任何地方将循环设置为false?我看不到它。如果没有,请尝试在大的else块结束时将循环设置为false。

示例:

else {
        if(dealersTotal > 21){
          outcome = 'player wins!';
        }
        else if(playersTotal > dealersTotal){
          outcome = 'player wins!'; 
        }
        else if (playersTotal == dealersTotal){
          outcome = 'tie!';
        }
        else if (dealersTotal > playersTotal){
          outcome = 'dealer wins!';
        }
        else {
          console.log('got here');
        }
        console.log(outcome);
        this.setState({resultOutcome: outcome});
        looping = false;
   }