我可以使用以下代码中的if条件查找本地存储密钥是否存在
this.data = localStorage.getItem('education');
if(this.data)//check if it exists or not empty
{
console.log("Exists");
}
如果想使用if条件来查找它是否不存在,我该如何在代码中写入?我不想用别的。请指导
如果this.data
是undefined
,那么!(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