简体   繁体   中英

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). 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.

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:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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