本地存储问题中的JSON.parse() [英] JSON.parse() from localStorage issue

查看:74
本文介绍了本地存储问题中的JSON.parse()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发一款小型浏览器游戏,并且正在使用HTML localStorage保存一些数据.

I am currently working on a little browser game and I am using the HTML localStorage to save some data.

问题: 我有一个空数组,以后我将.push()放入一些数据中.我将此数组存储在localStorage中,但是当我尝试从本地存储中读取它不起作用时.

The problem: I have an empty array that i will later .push() some data into. I am storing this array in the localStorage but when i try to read from the local storage it doesn't work.

Chrome开发者工具控制台出现以下错误: 尝试从localStorage解析数据时出现"Uncaught SyntaxError:意外的令牌u".

The Chrome Developer Tools console is giving me this error: "Uncaught SyntaxError: Unexpected token u" when trying to parse the data from localStorage.

这是我正在使用的代码:

Here's the code i am using:

var allContracts = [];
localStorage["allContracts"] = JSON.stringify(allContracts);

allContracts = JSON.parse(localStorage["allContracts"]);

代码比这更多,但是没有一个代码与这些代码有任何交互.

There is more code than this but none of it is interacting with these in any way.

是否存在我不知道的导致localStorage或JSON的古怪现象? (我对JSON或localStorage不太熟悉) 我应该以其他方式执行此操作吗? 还是我只是错过了一个明显的错误?

Is there a quirk with localStorage or JSON that i am not aware of and is causing this? (i am not very familiar with JSON or localStorage) Should i be doing this a different way? Or am i just missing an obvious mistake?

先谢谢您了:)

推荐答案

最好的方法是使用localStorage接口为您服务的方法.它具有setItem()getItem()方法,那么为什么不使用它来保护自己呢?

The best way is to use the methods that the interface of localStorage serves to you. It have setItem() and getItem() methods, so why not use to safe yourself?

var allContracts = [];
// setter
localStorage.setItem("allContracts",  JSON.stringify(allContracts));
//getter
var allContracts = JSON.parse(localStorage.getItem("allContracts"));

用您的代码,用您自己的值覆盖localStorage全局对象,因此您失去了功能.

With your piece of code, you are overriding the localStorage global object with your own values, so you lost the functionality.

您这样做:

localStorage = [] // transform the default localstorage into an array

您需要这个:

localStorage.setItem(key, value)

更多信息: https://developer.mozilla.org /en-US/docs/Web/API/Window/localStorage

这篇关于本地存储问题中的JSON.parse()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆