gpt4 book ai didi

javascript - 如何将值作为列表添加到 localStorage 中?

转载 作者:行者123 更新时间:2023-11-29 16:38:02 28 4
gpt4 key购买 nike

我使用以下命令将值添加到本地存储:

var thisId = "<?php echo $id; ?>";
localStorage.setItem("postId", thisId);
console.log(localStorage.getItem("postId"));

以下内容每次都会为我最终进入的每个页面加载:

<?php echo $id; ?>

所以它会变成:242248

事情是每次我做 console.log(localStorage.getItem("postId")); 我只得到一个值,因为它不是作为值列表添加,而是用旧的替换新的。

最佳答案

改用列表。由于您只能将字符串存储到localStorage中,因此最好的方法是使用JSON解析/字符串化方法来帮助您进行数据序列化。

  • 以列表形式获取本地存储项 (JSON.parse)
  • 添加项目
  • 将列表保存到本地存储 (JSON.stringify)

var thisId = "1";//<?php echo $id; ?>

var localList = localStorage.getItem("postIdList") || "[]";
localList = JSON.parse(localList);

//Check repeated ID
var isExistingId = localList.indexOf(thisId) > -1;
if (!isExistingId) {
localList.push(thisId);
}

localStorage.setItem("postIdList", JSON.stringify(localList));
console.log(localStorage.getItem("postIdList"));

关于javascript - 如何将值作为列表添加到 localStorage 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49511011/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com