检查是否存在任何Key localStorage Javascript

问题描述 投票:0回答:2

我需要检查localStorage中是否有任何密钥此代码不起作用

    if (localStorage.user === undefined) {
      alert('There is no key!'); 
    }
javascript local-storage web-storage
2个回答
0
投票
if (Object.keys(localStorage).length === 0) {
  alert('There is no key!'); 
}

0
投票

你需要使用getItem

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

编辑您可以检查本地存储是否为空

if (localStorage.length == 0)
© www.soinside.com 2019 - 2024. All rights reserved.