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

无法正确输出用户输入数组:10人名单录入程序问题咨询

问题修正方案

你的代码存在几个逻辑和语法问题,导致无法正确触发超出数量后的提示,以下是具体问题和修正后的代码:

原代码问题点

  • 循环逻辑错误:设置size = 11后,循环执行11次(i从0到10),但判断条件i < size永远为真,第11次循环仍会弹出输入框,无法触发提示。
  • 条件判断语法错误:else if (i = 11)是赋值操作,不是比较(正确应为i === 11),且i最大值为10,该分支永远不会执行。
  • 字符串格式错误:prompt中的换行未转义,会导致JavaScript语法报错。
  • 数组赋值不严谨:直接通过inputArray[i]赋值,若用户取消输入会导致数组出现undefined,用push更稳妥。

修正后的代码(贴合你的原始思路)

let inputArray = [];
const maxInvites = 10;

for (let i = 0; i <= maxInvites; i++) {
    if (i < maxInvites) {
        // 用模板字符串修复换行问题,优化提示文本
        const name = prompt(`Please enter the name of person ${i + 1} you'd like to invite to the party`);
        inputArray.push(name);
    } else {
        // 第11次循环时触发提示并输出列表
        console.log("You have already invited 10 people");
        console.log("Invited list:", inputArray);
    }
}

更健壮的版本(支持用户中途取消输入)

let inputArray = [];
const maxInvites = 10;

while (inputArray.length < maxInvites) {
    const name = prompt(`Please enter the name of person ${inputArray.length + 1} you'd like to invite to the party`);
    // 用户点击取消时退出循环
    if (name === null) break;
    inputArray.push(name);
}

// 输入满10个时触发提示
if (inputArray.length === maxInvites) {
    console.log("You have already invited 10 people");
    console.log("Invited people:", inputArray);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 06:20:09