本地存储和JSON.parse:如果没有值,JS就会停止工作?
抱歉,如果标题有什么误解。 如果我尝试使用 json 解析本地存储中的值并且没有值,则无法正常工作,那么我在使用 Web 应用程序时遇到了一些问题。
例如:
如果您执行以下操作: alert(localStorage.getItem("something"));
您将得到 null:http://jsfiddle.net/yrGht/
但如果你这样做它会阻止一切: alert(JSON.parse(localStorage["test"]));
你会得到什么也没有和它阻止一切工作: http://jsfiddle.net/7tCaS/
我怎样才能解决这个问题,以便我警告第一个,如果它没有值,则继续工作,因为基本上我想将其设置为: JSON.parse(localStorage["test"])
作为全局变量,但它会阻止其他所有内容:http://jsfiddle.net/gq9Ea/
Sorry if the title is somehow misunderstanding.
I am having some problems with a web app if I try to parse values from a localstorage using json and there are no values, nothing works.
For example:
If you do this: alert(localStorage.getItem("something"));
you get null: http://jsfiddle.net/yrGht/
but if you do this it blocks everything: alert(JSON.parse(localStorage["test"]));
you get nothing and it stops everything from working: http://jsfiddle.net/7tCaS/
How can I solve this so that I alert the first and if it has no value then keep working because basically I want to set this: JSON.parse(localStorage["test"])
as a global variable but it blocks everything else: http://jsfiddle.net/gq9Ea/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个:
失败的原因是
JSON.parse(undefined_variable)
给出“无效字符”错误。如果localStorage['test']
不存在,则它是undefined
,因此会出现错误。如果该值为假(未定义
),则上面的代码会将null
置于适当的位置。但是,如果值为0
、""
或其他虚假值,这确实会产生不良影响。如果需要更具体的代码,请尝试:Try this:
The reason it fails is because
JSON.parse(undefined_variable)
gives an "invalid character" error. IflocalStorage['test']
doesn't exist, it'sundefined
, so it gets an error. The above code putsnull
in place if the value is falsy, whichundefined
is. However this does have ill effects if the value is0
,""
or another falsy value. If more specific code is needed, try:使用 localStorage 时,您需要在编码中预期数据可能不存在,并且需要测试该情况并以某种方式处理它。最简单的方法是这样的:
您还可以使用异常处理:
此外,您应该学习如何在浏览器错误控制台或调试器控制台中查看 javascript 错误。 JavaScript 并没有被“阻止”。它引发了一个未处理的错误,因此执行被中止。该错误(行号和错误类型)均记录在错误控制台和调试器控制台中,供您查看。
When using localStorage, you need to anticipate in your coding that the data might not be there and you need to test for that condition and handle it in some way. The simplest way to do that would be something like this:
You could also use exception handling:
In addition, you should learn how to see your javascript errors in the browser error console or the debugger console. Javascript wasn't "blocked". It threw an error which was unhandled so execution was aborted. That error (both line number and type of error) was logged in both the error console and the debugger console for you to see.