如何检查本地存储密钥是否不存在?

问题描述 投票:1回答:1

我可以使用以下代码中的if条件查找本地存储密钥是否存在

    this.data = localStorage.getItem('education'); 
      if(this.data)//check if it exists or not empty
{
        console.log("Exists");
      }

如果想使用if条件来查找它是否不存在,我该如何在代码中写入?我不想用别的。请指导

angular typescript
1个回答
2
投票

如果this.dataundefined,那么!(this.data)应该起作用:

if (!(this.data)) { console.log("DOH!"); }

编辑:我刚收到一条提出意见的评论。如果关键是false怎么办?那还不够。如果密钥实际存在并且设置为undefined怎么办?那么该方法将失败。因此,最好使用in关键字(如this answer中所述)

if (!("data" in this)) { console.log("DOH!"); }

例如:

obj = { a: false, b: undefined }
if (!("a" in obj)) { console.log("a does not exist"); }
if (!("b" in obj)) { console.log("b does not exist"); }
if (!("c" in obj)) { console.log("c does not exist"); }

输出是

c does not exist
© www.soinside.com 2019 - 2024. All rights reserved.