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

如何修改代码实现在localStorage中新增对象而非覆盖原有数据?

解决localStorage添加对象不覆盖原有数据的问题

你的代码每次执行都会覆盖旧数据,核心原因是每次都把notesObj初始化成了空数组,完全没读取 localStorage 里已有的内容。要实现新增而非覆盖,得先把已存的笔记读出来,再把新笔记加进去,最后存回去。

修改后的代码如下:

function addNote() {
    const givenTitle = document.getElementById('titleInput');
    const givenNote = document.getElementById('noteInput');

    // 先读取localStorage里已有的笔记,没有的话设为空数组
    let notesObj = JSON.parse(localStorage.getItem('userNote')) || [];

    // 创建新笔记对象,去除首尾空格
    let myObj = {
        title: givenTitle.value.trim(),
        note: givenNote.value.trim(),
    };

    // 避免存入空内容
    if (myObj.title || myObj.note) {
        notesObj.push(myObj);
        // 把更新后的数组存回localStorage
        localStorage.setItem('userNote', JSON.stringify(notesObj));
        // 清空输入框(可选优化)
        givenTitle.value = '';
        givenNote.value = '';
    }
}

关键改动说明:

  • 用JSON.parse(localStorage.getItem('userNote')) || []读取已有数据:如果userNote不存在(第一次执行),就用空数组兜底,避免JSON.parse(null)返回null导致后续push报错。
  • 新增了输入内容的trim()处理和空值判断,防止存入无意义的空笔记。
  • 可选添加清空输入框的逻辑,提升用户体验。

内容的提问来源于stack exchange,提问作者Dinesh Chandra Pandey

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 01:22:41