我如何检查一个项目是否设置在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?
}

其他回答

你可以使用hasOwnProperty方法来检查

> localStorage.setItem('foo', 123)
undefined
> localStorage.hasOwnProperty('foo')
true
> localStorage.hasOwnProperty('bar')
false

适用于当前版本的Chrome(Mac), Firefox(Mac)和Safari。

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

方法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是否存在键(或键值)很容易用localDataStorage完成,这是我创建的一个方便的实用程序包装器。

在用类似

myLDS = localDataStorage( 'segmentedStorageHere' );

你可以设置按键

myLDS.set( 'infiniteScrollEnabled', true );

以直截了当的方式。注意,这个示例实际上是将一个布尔值传递给存储,在存储中可以使用

let scrollingState = myLDS.get( 'infiniteScrollEnabled' );

scrollingState将包含返回的布尔值。包装为您跟踪本机JavaScript数据类型,无缝(数组,布尔,日期,数字,对象等)没有更多的JSON字符串/解析在您的代码。

现在,当我们需要知道一个钥匙是否在存储中,我们可以像这样检查它

if( myLDS.haskey( 'infiniteScrollEnabled' ) ) {
    console.log( "It's been set!" ); 
} else {
    console.log( "The key is not set." ); 
}

您还可以检查是否存在特定的值。例如

myLDS.set( 'myNumber', 1234.5678 );
console.log( myLDS.hasval( 1234.5678 ) );    --> true
if(!localStorage.hash) localStorage.hash = "thinkdj";

Or

var secret =  localStorage.hash || 42;

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

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

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