检查是否存在任何Key localStorage Javascript

时间:2017-12-16 11:37:08

标签: javascript local-storage web-storage

我需要检查localStorage中是否有任何密钥 此代码无效

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

2 个答案:

答案 0 :(得分:0)

您需要使用getItem

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

修改 您可以通过

检查localstorage是否为空
if (localStorage.length == 0)

答案 1 :(得分:0)

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