Javascript 当用户连接时,从localStorage设置数据
我一直在为我的游戏制作一个保存文件。保存文件正在工作,并且console.log显示正确的值:Javascript 当用户连接时,从localStorage设置数据,javascript,save,Javascript,Save,我一直在为我的游戏制作一个保存文件。保存文件正在工作,并且console.log显示正确的值: function saveGame(){ localStorage.setItem('game', JSON.stringify(game)); } function loadGame(){ var retrievedObject = localStorage.getItem('game'); console.log('retrievedObject: ', JSON.pars
function saveGame(){
localStorage.setItem('game', JSON.stringify(game));
}
function loadGame(){
var retrievedObject = localStorage.getItem('game');
console.log('retrievedObject: ', JSON.parse(retrievedObject));
}
日志的图像:
我对这一切还是新手,因为我几个月前就开始学习JS了。现在我的猜测是,当页面加载时,我应该设置所有这些值。尝试下一件事,我在console.log中得到“null”
console.log(JSON.parse(localStorage.getItem('game.plutonium')));
我认为可以设置如下值:
game.plutonium = localStorage.getItem('game.plutonium');
但它不起作用。这里有什么诀窍
以下是我的完整JS代码,以防万一:
值是从第1行定义的,保存/加载文件在第350-356行。
为什么我的方法不起作用
function saveGame(){
var savefile = JSON.stringify(game);
localStorage.setItem("game", savefile);
}
function loadGame(){
var savefile = localStorage.getItem("game");
if (savefile === null) {
return;
}
game = JSON.parse(savefile);
}
上述方法似乎已经完全解决了这个问题。谢谢:)JSON.stringify()
将您提供的对象更改为字符串(可以很容易地存储)。但是:您不能再通过string.key
要将该json字符串转换回一个对象(可以再次导航),需要使用json.parse()
您上面的问题是,您使用键game
将整个对象(作为json)存储到存储器中,然后尝试从存储器中获取项目game.puropoium
。请注意,您没有将任何内容保存为game.puropoium
var game = JSON.parse(localStorage.getItem('game'))
var plutonium = game.plutonium;
您需要首先通过localStorage.getItem('game')
获取整个json字符串,然后将字符串解析回一个对象,然后才能像game.puropoium
一样再次浏览它
var game = JSON.parse(localStorage.getItem('game'))
var plutonium = game.plutonium;
我已经设法让它使用函数saveGame(){var savefile=JSON.stringify(game);localStorage.setItem(“game”,savefile);}函数loadGame(){var savefile=localStorage.getItem(“game”);game=JSON.parse(savefile);}但问题现在发生在gamestart上。若我加载游戏,而本地存储是空的,那个么游戏就不工作了。如果我先保存游戏,那么我将始终覆盖保存的数据。。。我试图找到一个使用布尔值的解决方案。你需要检查你从本地存储中获得的项目是否已经存在,然后才将其加载到你的游戏对象中。如果它不存在(
getItem()
返回null),则使用一些默认值填充游戏对象(不存在savegame;首先开始)