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

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

当前回答

可以尝试这样做:

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

其他回答

为真正的

localStorage.infiniteScrollEnabled = 1;

因为假

localStorage.removeItem("infiniteScrollEnabled")

检查存在

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

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

可以尝试这样做:

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

你可以使用hasOwnProperty方法来检查

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

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

我来晚了,但是检查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