首页 > 解决方案 > 如何停止本地存储覆盖

问题描述

我不太了解本地存储,所以我希望我能正确解释这一点。在没有进入我的程序上下文的情况下,我基本上希望每次运行程序时都设置两个键值,“teamname”和“totalpoints”,但是每次运行程序时,这些值都会被覆盖到最近一次他们被设置了。我在某个地方看到我需要合并一个数组来解决这个问题,但是我真的不知道该怎么做。

function store()
{
localStorage.setItem("key value",[teamname, totalpoints]);
document.write(localStorage.getItem("key value"));
}

标签: javascriptlocal-storageoverwrite

解决方案


如果我理解您的问题,您只需要某种方式来检查用户的状态,如果他们已经访问过,请不要覆盖他们的团队名称或分数:

let teamname
let totalpoints

if(localStorage.getItem("visited") !== "true"){
   teamname = /* your code here */
   totalpoints = /* your code here */

   localStorage.setItem("teamname", teamname)
   localStorage.setItem("totalpoints", totalpoints)
   localStorage.setItem("visited", true)
}else{
   /* do something else */
}

推荐阅读