简体   繁体   English

我的本地存储无法保存,不知道为什么,第一次使用它

[英]my local storage fails to save, no idea why, first time using it

i got this function that's executed upon other things upon page load, it does save the items correctly till the page is refreshed, i want to use that array to calculate maximum score from it on future games, some explanation would help first time using JSON aswell我得到了在页面加载时在其他事情上执行的这个函数,它确实正确保存了项目直到页面刷新,我想使用该数组来计算未来游戏中的最大分数,一些解释也有助于第一次使用 JSON

the code:编码:

localStorage.setItem("scroes", JSON.stringify(gBestScores));
    var retrievedData = localStorage.getItem("scroes");
    gscores = JSON.parse(retrievedData);

gBestScores is an empty array that gets pushed a value each time the game ends or is restarted, not saved in localstorage, checked and works fine, gScores is an undefined variable at the top of the page, tried setting it to an empty array didnt make much difference gBestScores 是一个空数组,每次游戏结束或重新启动时都会推送一个值,未保存在本地存储中,检查并正常工作,gScores 是页面顶部的未定义变量,尝试将其设置为空数组没有成功差别很大

The code as it is doesn't load the scores up or save the scores properly.代码本身不会加载分数或正确保存分数。

It should be:它应该是:

When the page / game load up, or before you need to display them or have them for insertion:当页面/游戏加载时,或者在您需要显示它们或让它们插入之前:

var retrievedData = localStorage.getItem("scores");
gscores = JSON.parse(retrievedData);

When the game ends:游戏结束时:

// if game score is higher than the best scores, insert it into gBestScores
localStorage.setItem("scores", JSON.stringify(gBestScores));

Also, wouldn't you use the same array for the highest scores?另外,您不会对最高分使用相同的数组吗? Right now you are using two: gscores and gBestScores .现在您正在使用两个: gscoresgBestScores

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

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