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

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

当前回答

试试这段代码

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

} else {

}

其他回答

你可以使用hasOwnProperty方法来检查

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

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

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

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

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

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

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

它不打印“hello”。

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

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

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

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