简体   繁体   English

如何让 localStorage 数据持久化

[英]How to have localStorage data persist

I'm kind of racking my brain over how to get data to persist in localStorage while also adding new data.我有点绞尽脑汁思考如何让数据持久保存在 localStorage 中,同时还添加新数据。 The jist of what I'm doing is creating a quiz that will store the users initials and their score into localStorage so that when refreshed and the user chooses to retrieve the high scores they'll be displayed.我正在做的主要是创建一个测验,将用户的姓名首字母和他们的分数存储到 localStorage 中,这样当刷新并且用户选择检索高分时,他们就会显示出来。 I'm having trouble where it gets to the end of my app and the data that's already there is completely overwritten.我在应用程序结束时遇到问题,并且已经存在的数据被完全覆盖。 Any help is appreciated.任何帮助表示赞赏。

function saveScore() {
    var data = [{name: userInitialsEl.value}, {score: scoreCount}];
    localStorage.setItem("high-score", JSON.stringify(data));
}

userInitialsEl is a text input. userInitialsEl 是一个文本输入。 scoreCount is the score that's incremented as the user answers questions correctly. scoreCount 是随着用户正确回答问题而增加的分数。

You need to get the current data first then push in the new one before saving it back, you can do something like this:您需要先获取当前数据,然后将新数据推入,然后再将其保存回来,您可以执行以下操作:

function saveScore() {
  let newData = !!localStorage.getItem("high-score") ? JSON.parse(localStorage.getItem("high-score")) : []
  newData.push([{name: userInitialsEl.value}, {score: scoreCount}])
  localStorage.setItem("high-score", JSON.stringify(newData));
    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM