javascript本地存储查找是否存在

javascript local storage find out if exists

本文关键字:是否 存在 查找 存储 javascript      更新时间:2023-09-26

如果本地存储中不存在localscores,我会使用以下内容来创建一个伪高分表:

if (localStorage.getItem("localScores") === null) {
highscores = [
  {user: "Player 1", score: 100},
  {user: "Player 2", score: 90},
  {user: "Player 3", score: 80},
  {user: "Player 4", score: 70},
  {user: "Player 5", score: 60},
  {user: "Player 6", score: 50},
  {user: "Player 7", score: 40},
  {user: "Player 8", score: 30},
  {user: "Player 9", score: 20},
  {user: "Player 10", score: 10}
  ];
  localStorage['localScores']=JSON.stringify(highscores);
  console.log("doesn't exist")
}
else{
highscores = JSON.parse(localStorage['localScores']);
console.log("exists")
}

我总是想保持10分,所以我用这个来添加分数,其中用户名和总数是输入的名称和获得的分数:

highscores.push({user: username, score: total});                               
highscores.sort(function(a,b){ return b.score - a.score});    
delete highscores[10];
localStorage['localScores']=JSON.stringify(highscores);
console.log(highscores);

一切都很好,直到我重新加载游戏并运行第一个函数,它似乎向highcores数组添加了null值。所以,如果我加上5个额外的分数,数组中就会有3个空值?

[对象,对象,对象

这让我相信,要么我评估当地分数是否存在的那条线是错误的(localStorage.getItem("localScores")===null)

或者我删除数组中第11个元素的位置是错误的删除高音[10];

或者还有其他问题我看不出来,如果有人知道发生了什么,我会非常感谢你的帮助。

在Array实例上调用delete时,实际上并没有缩短数组,只是用undefined替换指定索引处的值。

如果highscores的长度始终不大于10,并且要删除的项目始终是最后一个,则可以简单地使用highscores.length = 10

您也可以使用highscores = highscores.slice(0,10);,但正如jfriend00所指出的,它确实涉及到创建新数组的额外开销。

尽管如此,我还是不得不提到,与浏览器编码/解码JSON和从localStorage读取/写入的工作量相比,创建新阵列的性能打击实际上只是杯水车薪,而localStorage是出了名的慢。

您可以使用highcores.pop()而不是delete highscores[10];