JSON.解析localStorage输入结束错误

JSON.parse localStorage unexpected end of input error

本文关键字:结束 错误 输入 localStorage 解析 JSON      更新时间:2023-09-26

这一行

item = JSON.parse(localStorage["item"]);
当我的localstorage没有值时,

导致我的控制台显示Uncaught SyntaxError: Unexpected end of input错误?如何解决这个问题?我知道空字符串不是一个有效的json。

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