Javascript 即使在空检查后本地存储也为空?
在我当前的项目中,我使用javascripts localStorage来存储一些数据。因为这个数据是在事后解析的,所以如果它还不存在,我需要将它设置为默认值。为此,我使用了一个简单的if检查:不幸的是,它不起作用。这是我的密码:Javascript 即使在空检查后本地存储也为空?,javascript,if-statement,null,local-storage,Javascript,If Statement,Null,Local Storage,在我当前的项目中,我使用javascripts localStorage来存储一些数据。因为这个数据是在事后解析的,所以如果它还不存在,我需要将它设置为默认值。为此,我使用了一个简单的if检查:不幸的是,它不起作用。这是我的密码: localStorage.setItem("myItem", null); //Test for the if-check. But even without it isnt working. if(localStorage.getItem("myItem")
localStorage.setItem("myItem", null); //Test for the if-check. But even without it isnt working.
if(localStorage.getItem("myItem") == undefined || localStorage.getItem("myItem") == null || localStorage.getItem("myItem") == ""){
console.log("is null");
localStorage.setItem("myItem", "myDefaultContent");
}
console.log(localStorage.getItem("myItem")); //null!
如何解决此问题?当您设置
localStorage.setItem(“myItem”,null)时
您确实将myItem
设置为字符串“null”,而不是null
类型。请记住,localStorage
值始终是字符串。在您的例子中,null
在存储之前被转换为字符串
那么支票呢
localStorage.getItem("myItem") == null || localStorage.getItem("myItem") == undefined
当然是false
,并且从不设置默认值
如果将myItem
设置为“null”
字符串,则还应检查字符串:
localStorage.getItem("myItem") === "null"
或者更好的方法是,首先不要设置
null
,空/未定义的比较将按预期工作。运行typeof localStorage.getItem(“myItem”)
非常感谢您,我从来没有想过!现在一切都好了,不客气!因为WebStorage值是字符串,所以为了存储对象和数组,我们使用JSON.stringify获取一个字符串,然后保存它。