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

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

当前回答

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
}

WebStorage规范中的getItem方法,如果项不存在,则显式返回null:

... 如果给定的键在与该对象关联的列表中不存在,则该方法必须返回null. ...

所以,你可以:

if (localStorage.getItem("infiniteScrollEnabled") === null) {
  //...
}

请看这个相关问题:

在HTML5 localStorage中存储对象

可以尝试这样做:

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

您应该在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?
}

最短的方法是使用默认值,如果key不在存储中:

var sValue = localStorage['my.token'] || ''; /* for strings */
var iValue = localStorage['my.token'] || 0; /* for integers */