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

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

当前回答

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

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

所以,你可以:

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

请看这个相关问题:

在HTML5 localStorage中存储对象

其他回答

我在这里添加了一些方法来检查

方法1

if("infiniteScrollEnabled" in localStorage){
     console.log("Item exists in localstorage");
}else{
    console.log("Item does not exist in localstoarge";
}

方法2

if(localStorage.getItem("infiniteScrollEnabled") === null){
    console.log("Item does not exist in localstoarge";
}else{
   console.log("Item exists in localstorage");
}

方法3

if(typeof localStorage["cart"] === "undefined"){
    console.log("Item does not exist in localstoarge";
}else{
   console.log("Item exists in localstorage");
}

方法4

if(localStorage.hasOwnProperty("infiniteScrollEnabled")){
     console.log("Item exists in localstorage");
 }else{
    console.log("Item does not exist in localstoarge";
 }
localStorage['root2']=null;

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

也许最好先看一遍计划?

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

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

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

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

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

所以,你可以:

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

请看这个相关问题:

在HTML5 localStorage中存储对象

为真正的

localStorage.infiniteScrollEnabled = 1;

因为假

localStorage.removeItem("infiniteScrollEnabled")

检查存在

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