我是编程新手,所以我总是遇到所有问题,我希望math.random随机选择1个问题并提出问题并将答案记录在控制台上,但我不断收到所有问题的提示
var langquestion = prompt('what is the best language?');
var progquestion = prompt('how many years have you been programming?');
var drivequestion = prompt('does veronica drive good?');
var ran = Math.random() * 10;
if (ran < 3) {
if (langquestion === 'javascript') {
console.log('correct');
} else {
console.log('wrong');
}
} else if (ran < 6 && ran > 3) {
if (progquestion < 2) {
console.log('keep working hard');
} else if (progquestion > 2 && progquestion < 5) {
console.log('your a programmer');
} else {
console.log('your the man');
}
} else {
if (drivequestion === 'yes'){
console.log('correct');
} else {
console.log('wrong');
}
};
;
答案 0 :(得分:1)
您的问题是您连续prompt
在代码的前三行中多次。
由于您的问题使用不同的逻辑来处理答案,因此可以这样构造代码:
var questions = [
{
text: 'What is the best language?',
handler: function(answer) {
return answer === 'javascript' ? 'Correct' : 'Wrong';
}
},
{
text: 'How many years have you been programming?',
handler: function(answer) {
if (answer < 2) return 'Keep working hard';
else if (answer < 5) return 'You\'re a programmer';
else return 'You\'re the man';
}
},
{
text: 'Does veronica drive well?',
handler: function(answer) {
return answer === 'yes' ? 'Correct' : 'Wrong';
}
}
];
var rand = Math.floor(Math.random() * questions.length),
question = questions[rand],
answer = prompt(question.text);
console.log(question.handler(answer));