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

如何根据输入数量让JavaScript弹窗正确显示?

问题分析与修复方案

核心问题1:条件判断误用赋值运算符

你写的 if (keepRunning = false) 是赋值操作(把false赋值给keepRunning),而非相等判断,导致这个条件永远返回false,alert代码块完全不会执行。需要改成相等判断:if (keepRunning === false),或者更简洁的if (!keepRunning)。

核心问题2:依赖循环变量i存在隐患

循环结束后i的值等于colorNames.length,但直接用colorNames.length统计输入数量更直观,也能避免变量作用域带来的潜在问题。

额外问题:未处理prompt取消的情况

当用户点击prompt的「取消」按钮时,newColor会返回null,此时访问newColor.length会直接报错,必须先判断newColor是否存在。

修复后的完整代码

// 循环相关变量
var colorNames = [];
var keepRunning = true;

// 持续输入颜色直到停止
while (keepRunning) {
    var newColor = prompt('Name as many colors as you can!' + "\n" + 'If you can\'t think of any more, leave empty and hit OK.');

    // 处理用户点击取消的情况
    if (newColor === null) {
        keepRunning = false;
        break;
    }
    // 判断输入是否为空
    if (newColor.length > 0) {
        colorNames.push(newColor);
    } else {
        keepRunning = false;
    }
}

// 显示输入的颜色名称
for (var i = 0; i < colorNames.length; i++) {
    var cName = colorNames[i];
    document.write(cName + "  ");
}

// 根据输入数量弹出提示
var colorCount = colorNames.length;
if (!keepRunning) {
    if (colorCount <= 4) {
        alert('That\'s all you could think of? Refresh and try again!')
    } else if (colorCount <= 8) {
        alert('Not bad, but you can probably do better. Refresh to play again.')
    } else if (colorCount <= 12) {
        alert('Wow! You really know your colors! You can refresh to challenge yourself again!')
    } else if (colorCount <= 14) { // 补充13-14个颜色的提示分支
        alert('Incredible! You\'re a color master in the making! Refresh to go again!')
    } else {
        alert('I don\'t think anyone could do better than this, nice job!')
    }
}

关键修改总结

  • 修正条件判断的运算符错误,确保alert代码块能正常触发
  • 新增prompt取消操作的处理逻辑,避免报错
  • 改用数组长度统计输入数量,逻辑更清晰稳定
  • 补充了原代码遗漏的13-14个颜色的提示场景

内容的提问来源于stack exchange,提问作者Tavish F

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 13:37:41