【问题标题】:JSON.parse localStorage unexpected end of input errorJSON.parse localStorage 意外结束输入错误
【发布时间】:2015-06-01 10:49:57
【问题描述】:

这一行

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

当我的本地存储没有价值时,我的控制台中显示Uncaught SyntaxError: Unexpected end of input 导致错误?我该如何解决这个问题?我知道空字符串不是有效的 json。

【问题讨论】:

  • 因为空字符串是无效的json
  • @PatrickEvans 感谢您澄清这一点,但如何解决这个问题?
  • 简单测试先看字符串是否为空,如果不解析
  • @PatrickEvans localStorage["item"] !== "" ? JSON.parse(localStorage["item"]); 正确吗?

标签: javascript html local-storage


【解决方案1】:
if(localStorage["item"]){
  item = JSON.parse(localStorage["item"]);
}

【讨论】:

  • 只有在 localStorage 中存在“item”键时才会分配变量。如果键不存在,您可能希望将 item 设置为 null 或其他对您的代码安全的值(三元组将是一种干净的方法)。
  • 没有解释的代码很少有用。
猜你喜欢
  • 2021-07-26
  • 2012-11-25
  • 1970-01-01
  • 1970-01-01
  • 2020-11-18
  • 2018-05-01
  • 2021-05-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多