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

如何避免向Local Storage存储数据时重复覆盖键名

解决方案

方案1:利用localStorage.length生成递增键名

localStorage.length会返回当前本地存储中键值对的总数,直接用这个数值作为新键的序号,就能保证每次生成唯一的新键:

function setLocalStorage() {
    let data = document.getElementById('textBox').value;
    // 用当前存储条目数+1作为键的后缀,避免重复
    const newKey = "Key" + (localStorage.length + 1);
    localStorage.setItem(newKey, data);
    document.getElementById("textBox").value = "";
}

方案2:用时间戳作为唯一键名

Date.now()会生成当前毫秒级的时间戳,每个时间戳都是唯一的,用它作为键的后缀,完全不会出现键名重复的情况,实现更简单:

function setLocalStorage() {
    let data = document.getElementById('textBox').value;
    // 时间戳确保键名唯一
    const newKey = "Key_" + Date.now();
    localStorage.setItem(newKey, data);
    document.getElementById("textBox").value = "";
}

补充说明

  • 方案1的键名是连续递增的格式(如Key1、Key2、Key3...),适合需要按顺序查看存储内容的场景;
  • 方案2的键名包含时间戳(如Key_1700000000000),即使手动删除过旧的存储条目,也不会出现键名重复的问题,稳定性更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 08:42:43