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

JavaScript while循环运行异常求助:购物列表练习功能未实现

问题定位

  • 变量名错误:循环判断条件用的是lista,但你在循环内把新输入的值赋值给了l,lista的内容从来没有更新过,只要第一次输入不为空,循环就会无限执行,永远走不到取消后的展示环节
  • 标签结构错误:<li>是列表项标签,必须嵌套在<ul>或者<ol>标签内才能正常渲染

可直接运行的修复代码

<body>
<h1>SHOPPING EVERYWHERE!</h1>
<!-- 提前准备列表容器 -->
<ul></ul>
<script>
let inputVal = prompt('请输入要添加的购物项');
while (inputVal !== null) {
  document.write(`<li>${inputVal}</li>`);
  // 新输入赋值给同一个判断变量
  inputVal = prompt('请输入要添加的购物项');
}
</script>
</body>

更稳妥的优化方案

上面的代码直接修复了你的原有逻辑问题,更推荐用原生DOM操作替代document.write,避免页面加载完成后调用document.write清空原有内容的问题:

<body>
<h1>SHOPPING EVERYWHERE!</h1>
<ul id="shopList"></ul>
<script>
const listContainer = document.getElementById('shopList');
let inputVal = prompt('请输入要添加的购物项');
while (inputVal !== null) {
  const item = document.createElement('li');
  item.textContent = inputVal;
  listContainer.appendChild(item);
  inputVal = prompt('请输入要添加的购物项');
}
</script>
</body>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 04:45:10