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

求助:实现支持编辑、删除、添加操作的数组交互功能

问题修复与完整实现

先梳理你代码里的核心问题:

  • 变量名拼写错误:数组定义为assignments,循环里误写为assignment
  • 循环初始条件错误:assignin未初始化就进入while判断,会抛出引用错误
  • 语法错误:window.prompt后误用逗号,导致变量赋值逻辑混乱
  • 功能不完整:删除逻辑只写了一半,编辑、添加功能未实现
  • 页面输出方式不合理:document.write会覆盖整个页面,建议用DOM元素展示

以下是修正后的完整代码,包含展示、添加、删除、编辑功能:

// 初始化作业数组
const assignments = ["chapter1", "chapter2", "chapter3", "chapter4", "chapter5", 
                     "chapter6", "chapter7", "chapter8", "chapter9", "chapter10", 
                     "chapter11", "chapter12", "chapter13", "chapter14", "chapter15"];

// 创建页面展示容器
function renderAssignments() {
  const container = document.getElementById('assignments-container');
  container.innerHTML = '<h3>当前作业列表</h3>';
  assignments.forEach((item, index) => {
    const itemEl = document.createElement('div');
    itemEl.textContent = `${index + 1}. ${item}`;
    container.appendChild(itemEl);
  });
}

// 初始化页面
document.body.innerHTML = `
  <div id="assignments-container"></div>
  <button id="action-btn">打开操作菜单</button>
`;
renderAssignments();

// 操作逻辑
document.getElementById('action-btn').addEventListener('click', () => {
  while (true) {
    const action = prompt("请选择操作:\n1. 添加作业\n2. 删除作业\n3. 编辑作业\n4. 退出");
    
    if (!action || action === '4') break;

    switch(action) {
      case '1':
        const newItem = prompt("输入新作业名称:");
        if (newItem) assignments.push(newItem);
        renderAssignments();
        break;
      case '2':
        let deleteText = "请输入要删除的作业序号:\n";
        assignments.forEach((item, index) => {
          deleteText += `${index + 1}. ${item}\n`;
        });
        const deleteIndex = parseInt(prompt(deleteText)) - 1;
        if (deleteIndex >= 0 && deleteIndex < assignments.length) {
          assignments.splice(deleteIndex, 1);
          renderAssignments();
        } else {
          alert("无效序号,请重新输入");
        }
        break;
      case '3':
        let editText = "请输入要编辑的作业序号:\n";
        assignments.forEach((item, index) => {
          editText += `${index + 1}. ${item}\n`;
        });
        const editIndex = parseInt(prompt(editText)) - 1;
        if (editIndex >= 0 && editIndex < assignments.length) {
          const newName = prompt("输入新的作业名称:", assignments[editIndex]);
          if (newName) assignments[editIndex] = newName;
          renderAssignments();
        } else {
          alert("无效序号,请重新输入");
        }
        break;
      default:
        alert("无效操作,请选择1-4");
    }
  }
});

关键改进说明:

  • 用renderAssignments函数统一渲染数组内容,避免重复代码
  • 用DOM元素替代document.write,防止页面被覆盖
  • 用switch语句清晰区分不同操作逻辑
  • 添加序号选择,让用户操作更直观
  • 增加输入合法性校验,避免无效操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 16:10:21