我如何检查一个项目是否设置在localStorage?目前我正在使用

if (!(localStorage.getItem("infiniteScrollEnabled") == true || localStorage.getItem("infiniteScrollEnabled") == false)) {
    // init variable/set default variable for item
    localStorage.setItem("infiniteScrollEnabled", true);
}

当前回答

localStorage['root2']=null;

localStorage.getItem("root2") === null //false

也许最好先看一遍计划?

localStorage['root1']=187;
187
'root1' in localStorage
true

其他回答

如何测试localStorage中存在的项? 此方法适用于Internet explorer。

<script>
    try{
        localStorage.getItem("username");
    }catch(e){
        alert("we are in catch "+e.print);
    }
</script>

为真正的

localStorage.infiniteScrollEnabled = 1;

因为假

localStorage.removeItem("infiniteScrollEnabled")

检查存在

if (localStorage[""infiniteScrollEnabled""]) {
  //CODE IF ENABLED
}

我能建议的最好最安全的方法就是,

if(Object.prototype.hasOwnProperty.call(localStorage, 'infiniteScrollEnabled')){
    // init variable/set default variable for item
    localStorage.setItem("infiniteScrollEnabled", true);
}

这将通过ESLint的no-prototype-builtins规则。

我总是通过检查localStorage或sessionStorage的长度来检查它们是否被设置

if (sessionStorage.length > 0) {
  console.log("exists")
} else {
  console.log("not exists")
}


您应该在localStorage中检查项目的类型

if(localStorage.token !== null) {
   // this will only work if the token is set in the localStorage
}

if(typeof localStorage.token !== 'undefined') {
  // do something with token
}

if(typeof localStorage.token === 'undefined') {
  // token doesn't exist in the localStorage, maybe set it?
}