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

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

当前回答

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

方法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";
 }

其他回答

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

方法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中存在的项? 此方法适用于Internet explorer。

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

试试这段代码

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

} else {

}
if(!localStorage.hash) localStorage.hash = "thinkdj";

Or

var secret =  localStorage.hash || 42;

如果你想检查undefined,你也可以试试这个:

if (localStorage.user === undefined) {
    localStorage.user = "username";
}

getItem是一个方法,如果没有找到value则返回null。