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

使用forEach循环提示notes非函数,网页无法展示localStorage存储的笔记

问题排查与修复

核心错误分析

  • forEach报错"不是函数":你定义的notesObj是包含txt1数组的对象(结构为{txt1: [笔记内容]}),直接对整个对象调用forEach必然报错——只有数组才有forEach方法,应该遍历notesObj.txt1这个数组。
  • 笔记无法展示:
    1. showNotes函数错误地重复执行notes.txt1.push(),会把输入框内容再次添加到数组,导致数据重复,甚至添加空值
    2. 展示判断条件if(notes.length !=0)无效:notes是对象,没有length属性,永远不会进入赋值分支,页面自然不会更新
    3. 拼接HTML时第一个<div>标签漏写了开头的<,导致生成的HTML无效

修正后的完整代码

// 仅在localStorage无数据时初始化,避免覆盖已有笔记
if (!localStorage.getItem("notes")) {
  localStorage.setItem("notes", JSON.stringify({ txt1: [] }));
}

let btn1 = document.getElementById("btn1");
btn1.addEventListener("click", function (e) {
  let notes = JSON.parse(localStorage.getItem("notes"));
  let inputVal = document.getElementById("txt1").value.trim();
  // 非空内容才添加,避免空笔记
  if (inputVal) {
    notes.txt1.push(inputVal);
    localStorage.setItem("notes", JSON.stringify(notes));
    // 添加后清空输入框
    document.getElementById("txt1").value = "";
    showNotes();
  }
});

function showNotes() {
  let notesObj = JSON.parse(localStorage.getItem("notes"));
  let html = "";
  // 遍历txt1数组而非整个对象
  notesObj.txt1.forEach(function(element, index) {
    html += `
    <div class="mycard-2 mx-2 card" style="width: 18rem;">
      <div class="card-body">
        <h5 class="card-title">Note ${index + 1}</h5>
        <p class="card-text">${element}</p>
        <!-- 给每个删除按钮设置唯一ID,方便后续实现删除功能 -->
        <button class="btn btn-primary" id="btn2-${index}">delete note</button>
      </div>
    </div>`;
  });

  let notesElm = document.getElementById('notes');
  // 判断数组长度是否大于0
  if (notesObj.txt1.length > 0) {
    notesElm.innerHTML = html;
  } else {
    // 无笔记时显示友好提示
    notesElm.innerHTML = `<p>暂无笔记,添加一条试试吧</p>`;
  }
}

// 页面加载时自动展示已有笔记
showNotes();

额外优化说明

  • 初始化逻辑加了判断,防止刷新页面时覆盖已有笔记
  • 增加输入内容非空校验,避免生成无效空笔记
  • 添加笔记后自动清空输入框,提升操作体验
  • 给删除按钮设置唯一ID,为后续实现删除功能打下基础
  • 无笔记时显示提示文本,优化空状态体验

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 11:06:48