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

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

当前回答

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

其他回答

为真正的

localStorage.infiniteScrollEnabled = 1;

因为假

localStorage.removeItem("infiniteScrollEnabled")

检查存在

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

可以尝试这样做:

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

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

也许最好先看一遍计划?

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

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

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

正如@Christian C. Salvadó上面提到的,你可以做到 If (xxx === null){}

但是null也是一个假值,就像这样:

if (null){
console.log ("hello");
}

它不打印“hello”。