即使在空检查后,localStorage为null?

Fly*_*Fly 2 javascript null if-statement local-storage

在我目前的项目中,我使用javascripts localStorage来存储一些数据.由于此数据之后被解析,我需要将其设置为默认值(如果尚未存在).为此,我使用简单的if-check:不幸的是,它不起作用.这是我的代码:

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!
Run Code Online (Sandbox Code Playgroud)

我怎么解决这个问题?

dfs*_*fsq 5

当你设置localStorage.setItem("myItem", null);你真的设置myItem字符串 "null",而不是null键入.请记住,localStorage始终是String.在你的情况下null,在存储之前将其转换为字符串.

所以检查

localStorage.getItem("myItem") == null || localStorage.getItem("myItem") == undefined 
Run Code Online (Sandbox Code Playgroud)

false的,当然,和默认值永远不会设置.

如果你设置myItem"null"字符串,那么你也应该检查字符串:

localStorage.getItem("myItem") === "null"
Run Code Online (Sandbox Code Playgroud)

或者更好的是,不要设置null在第一位,并且null/undefined比较将按预期工作.