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

如何通过文本输入框实现数组元素的添加与删除(购物清单开发场景)

代码问题排查

你的代码存在以下核心错误:

  • 错误将DOM对象description赋值给数组变量groceryList,直接覆盖了原本存储商品的数组,导致所有数组操作失效
  • 没有编写渲染逻辑,未把数组内的商品内容更新到页面展示区域,仅赋值DOM对象不会触发页面更新
  • 删除函数未获取当前输入框的内容,只能拿到上次添加操作时的全局groceryitem值,无法匹配当前要删除的商品
  • 删除逻辑的循环条件错误:i <= groceryList.length会出现数组下标越界,且splice修改数组长度后,普通for循环会出现漏判问题,同时你把错误的赋值逻辑放在循环内执行,完全不符合需求
修复后可运行的完整代码
<body>
    My grocery list
    <br>
    <br>
    <div id="groceryinfo"></div>
    <br>
    <br>
    <input id="Button1" type="button" value="Add this item" onclick="Add()" />
    <input id="Text1" type="text" />
    <br>
    <input id="Button2" type="button" value="Remove this item" onclick="Remove()" />
    <script>
        var groceryList = [];
        var description = document.getElementById("groceryinfo");
        // 抽离公共渲染函数,数组变动后统一调用更新页面
        function renderList() {
            description.innerHTML = groceryList.join('<br>');
            // 渲染完成后清空输入框,可选优化
            document.getElementById('Text1').value = '';
        }

        function Add() {
            const groceryitem = document.getElementById('Text1').value.trim();
            // 加非空判断,避免添加空内容
            if (!groceryitem) return;
            groceryList.push(groceryitem);
            renderList();
        }

        function Remove() {
            const targetItem = document.getElementById('Text1').value.trim();
            if (!targetItem) return;
            const targetIndex = groceryList.indexOf(targetItem);
            // 找到对应元素才执行删除
            if (targetIndex > -1) {
                groceryList.splice(targetIndex, 1);
                renderList();
            }
        }
    </script>
</body>
逻辑说明
  • 单独抽离了renderList渲染函数,每次数组修改后调用该函数,将数组内所有商品按行展示在页面区域
  • 添加操作会先对输入内容做非空校验,避免添加无效空白内容
  • 删除操作直接通过indexOf匹配要删除的商品下标,匹配到后才执行删除,逻辑更简洁也避免了循环漏判问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 19:57:04