简体   繁体   English

有什么办法可以避免 localStorage.getItem() 的 key 的未定义值?

[英]Is there any way to avoid the undefined value of key of localStorage.getItem()?

There was the following key pair value in my local storage - instrument,BTX(key,value).我的本地存储中有以下密钥对值 - 仪器,BTX(键,值)。 I deleted the value manually from local storage.我从本地存储中手动删除了该值。 Now the value of this key is undefined.现在这个键的值是未定义的。 I have written this condition to avoid the undefined value, but it is not working.我写了这个条件来避免未定义的值,但它不起作用。 The issue here is that, although the value is undefined so the else block should be executed but here in all possible cases the if block is getting executed.这里的问题是,虽然该值是未定义的,所以应该执行 else 块,但在所有可能的情况下,if 块都会被执行。

First way:第一种方式:

if(localStorage.getItem("instrument")){}
else {}

Second way:第二种方式:

if(!!localStorage.getItem("instrument")){}
else {}

Third way:第三种方式:

if(localStorage.getItem("instrument")!==undefined){}
else {}

Try this尝试这个

if(localStorage.getItem("instrument")!=null){
// Do Something here
}else{
// Do Something Here
}

Hope it's working:)希望它的工作:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM