You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 08:54:21