简体   繁体   中英

Check if exist any Key localStorage Javascript

I need to check if there is any key in localStorage This code did not work

    if (localStorage.user === undefined) {
      alert('There is no key!'); 
    }

You need to use getItem

if (localStorage.getItem("user") === null) {
    alert('Não há chave!'); 
}

EDIT You can check if the localstorage is empty by

if (localStorage.length == 0)
if (Object.keys(localStorage).length === 0) {
  alert('There is no key!'); 
}

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