无法正确输出用户输入数组: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
相关产品推荐
相关产品推荐

