Javascript while循环终止而不执行语句

时间:2017-06-06 04:19:40

标签: javascript loops if-statement

我希望我的程序应该像以下一样:它应该一遍又一遍地向用户询问答案,直到正确的答案,并在最后的警报中提供完善的信息。

任何帮助,为什么它不会这样做????

var answer = prompt('What is the capital of Pakistan?');
while(answer != 'islamabad'){
  if(answer === 'islamabad'){
    alert('Your answer is correct!');
  }else if(answer != 'islamabad'){
    answer = prompt('Try again.');
  }else{
    alert('Well Done');
  }
}

1 个答案:

答案 0 :(得分:0)

此条件if(answer === 'islamabad')永远不会成立:您在检查if == islamabad的条件后检查if != islamabad

while(answer != 'islamabad'){
    if(answer === 'islamabad'){   ◄ this will never be true

尝试使用以下内容:

var answer = prompt('What is the capital of Pakistan?');
while(answer != 'islamabad'){       
    answer = prompt('Try again.');
}
alert('Well Done');