JS答题脚本未弹出题目prompt弹窗直接执行总分alert问题
故障根因
循环逻辑完全未执行,是属性拼写错误导致的:
- JavaScript数组的长度属性为
length,你在for循环的终止判断条件里错写为复数形式lengths - 运行时
questions.lengths是不存在的属性,返回值为undefined,判断式0 < undefined结果为false,for循环从一开始就不会进入执行,自然不会弹出任何题目prompt,直接跳到最后执行总得分的alert弹窗。
修复方案
只需要把循环条件里的questions.lengths改成questions.length即可,修复后的可运行代码如下:
var questions = [ { prompt:"What is the color of banana?\n(a)red\n(b)green\n(c)yellow", // \n = 换行 answer:"c" }, { prompt:"What is the color of strawberry?\n(a)red\n(b)green\n(c)yellow", answer:"a" }, { prompt:"how many centimeters is equal to One meter?\n(a)1\n(b)10\n(c)100", answer:"c" } ] var score = 0; for(var i=0; i<questions.length; i++){ var input=prompt(questions[i].prompt); if(input == questions[i].answer){ score++; alert("Answer Correct!"); }else{ alert("Answer Wrong!"); } } alert("Total correct answer: "+ score );
可选优化点
- 增加输入兼容:对用户输入做去空格、小写转换,避免用户输入大写选项(比如输入
C)、输入时带了多余空格被误判答错,判断条件可改为if(input?.trim().toLowerCase() === questions[i].answer) - 增加空值判断:用户点击prompt的取消按钮、或者未输入内容时,可以给出对应提示,避免直接判定答错。
内容的提问来源于stack exchange,提问作者Hercules
相关产品推荐
相关产品推荐

