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

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

当前回答

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

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

其他回答

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

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

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

为真正的

localStorage.infiniteScrollEnabled = 1;

因为假

localStorage.removeItem("infiniteScrollEnabled")

检查存在

if (localStorage[""infiniteScrollEnabled""]) {
  //CODE IF ENABLED
}
if(!localStorage.hash) localStorage.hash = "thinkdj";

Or

var secret =  localStorage.hash || 42;

我在我的项目中使用过,对我来说非常适合

var returnObjName= JSON.parse(localStorage.getItem('ObjName'));
if(returnObjName && Object.keys(returnObjName).length > 0){
   //Exist data in local storage
}else{
  //Non Exist data block
}

可以尝试这样做:

 let x = localStorage.getItem('infiniteScrollEnabled') === null ? "not found" : localStorage.getItem('infiniteScrollEnabled')