如何实现网页循环重复提问并保存多组不同答案?附代码问题求助
解决循环提问并保存多组答案的问题
嘿,我看了你的代码,问题主要出在没有全局容器存储多组答案,还有一些语法和逻辑小问题。咱们一步步来修复:
原代码的核心问题
- 每次循环都会重新创建
arr数组,之前的用户答案会被直接覆盖,根本没保存下来 - 判断空输入的逻辑错误:
arr[1] == []永远不会成立,prompt返回的是字符串或null,不是数组 arr.splice(4)的逻辑不对,splice是删除元素,不是设置默认值- 语法错误:
web ++ numWeb++缺少分号,会导致代码报错 prompt(arr)这行完全没必要,属于无效代码
修改后的完整代码
// 创建全局数组,用来存储所有用户的答案组 const allAnswers = []; let numWeb = 1; let web = 0; while (web < numWeb) { // 每次循环创建新的答案数组,存储当前用户的回答 const arr = []; arr[0] = prompt("What's your name?"); arr[1] = prompt("When were you born?"); arr[2] = prompt("What hobby do you love to do?"); arr[3] = prompt("Where do you live?"); arr[4] = prompt("Do you know Bill Gates?"); arr[5] = prompt("When did you graduate? (YYYY/MM/DD)"); // 处理空输入的默认值 if (!arr[1] || arr[1] === "") { arr[1] = "not given"; } if (!arr[4] || arr[4] === "") { arr[4] = "not given"; } // 将当前用户的答案组存入全局数组 allAnswers.push(arr); // 询问是否继续 const answer = prompt("Do you need to ask another person? Y/N"); if (answer?.toLowerCase() === "y") { numWeb++; } else if (answer?.toLowerCase() === "n") { // 啥也不用做,循环会自然结束 } else { alert("ERROR: Please enter Y or N"); // 错误输入时不递增web,重新询问 continue; } web++; } // 格式化输出所有答案 document.write("<h2>All Collected Answers:</h2>"); allAnswers.forEach((answers, index) => { document.write(`<h3>User ${index + 1}:</h3>`); document.write(`<ul>`); document.write(`<li>Name: ${answers[0] || "not given"}</li>`); document.write(`<li>Birth Date: ${answers[1]}</li>`); document.write(`<li>Hobby: ${answers[2] || "not given"}</li>`); document.write(`<li>Residence: ${answers[3] || "not given"}</li>`); document.write(`<li>Knew Bill Gates: ${answers[4]}</li>`); document.write(`<li>Graduation Date: ${answers[5] || "not given"}</li>`); document.write(`</ul>`); }); // 也可以在控制台查看原始数组 console.log("All answers stored:", allAnswers);
关键改动说明
- 全局存储容器:新增
allAnswers数组,每次循环把当前用户的arrpush进去,这样所有答案都会被保存 - 修正空值判断:用
!arr[1] || arr[1] === ""来判断用户是否没输入或点击了取消(prompt取消返回null,!null是true) - 修复语法错误:补充分号,移除无效的
prompt(arr)代码 - 优化输出:用HTML标签格式化展示多组答案,比直接写数组可读性高太多
- 错误处理优化:输入错误时用
continue跳过web递增,重新询问用户,避免直接结束循环
现在运行代码,就能循环收集多组用户答案,并且所有数据都会保存在allAnswers数组里啦!
内容的提问来源于stack exchange,提问作者Gordon chan




