如果您需要使用prompt()
,则必须确定误差范围,因为即使列表很长,您也不会涵盖所有可能性。否则,您可以替换为prompt()
,confirm()
因为这会给您带来回报true
,或者false
更容易处理。我强烈建议使用confirm()
,但如果prompt()
需要,一些选项如下:
特定选项数组
不是很好,因为组合非常有限,更多的可能性会产生更大的数组,另外你可能最终需要一个 indexOf polyfill(除非你添加一个自定义循环)
var questions = [{
question: 'Are you ready to play?',
answers: ['yep','yes','yea','yeah','hell yeah','hell yea','absolutely','duh','of course'],
affirm: 'Yay! You will be presented with a series of questions. If you answer a questions incorrectly, you cannot advance to the next...',
rebuttal: "No, you're definitely ready to play."
}];
if(questions[i].answers.indexOf(answer) > -1) //.indexOf may need polyfill depending on supported browsers
野兽般的正则表达式
更灵活并缩短代码以获得更多选项,但与直接字符串比较相比可能存在较小的性能问题
var questions = [{
question: 'Are you ready to play?',
answer: /((hell[sz]? )?ye[psa]h?|absolutely|duh|of course)!*/i, //matches "hell yea","hells yea","hellz yea","hell yeah","yep","yes","hellz yeah!","hell yesh" .... etc plus the full words at the end
affirm: 'Yay! You will be presented with a series of questions. If you answer a questions incorrectly, you cannot advance to the next...',
rebuttal: "No, you're definitely ready to play."
}];
if(questions[i].answer.test(answer))
正则表达式数组
结合前 2 个问题,但使正则表达式更易于管理
var questions = [{
question: 'Are you ready to play?',
answers: [/ye[psa]!*/,/(hell )?yeah?!*/,/absolutely!*/,/duh!*/,/of course!*/,/yeehaw!*/]
affirm: 'Yay! You will be presented with a series of questions. If you answer a questions incorrectly, you cannot advance to the next...',
rebuttal: "No, you're definitely ready to play."
}];
var saidYes = false;
for(var j=0,c=questions[i].answers.length;j<c;j++)
{
if(questions[i].answers[j].test(answer))
{
saidYes = true;
break;
}
}
使用confirm()——个人推荐
通过消除不同响应的可能性来简化整个过程
var answer = confirm(questions[i].question);
var correct = false;
while (correct === false)
{
if(answer)
{
alert(questions[i].affirm);
correct = true;
}
else
{
alert(questions[i].rebuttal);
answer = confirm(questions[i].question);
}
}