如何检查存储项是否已设置?

Jie*_*eng 261 javascript html5 local-storage

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

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

CMS*_*CMS 461

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

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

所以你可以:

if (localStorage.getItem("infiniteScrollEnabled") === null) {
  //...
}
Run Code Online (Sandbox Code Playgroud)

看到这个相关的问题:

  • 注释不正确 - 当前版本的`Storage`接口明确指出值的类型为`DOMString`.http://www.w3.org/TR/webstorage/#the-storage-interface (4认同)
  • @Paul:是的,你甚至可以扩充`Storage.prototype`对象,但根据经验,我总是建议[不要修改你不拥有的对象](http://www.nczonline.net/blog/ 2010/03/02/maintainable -javascript-dont-modify-objects-you-down-own /),特别是宿主对象. (3认同)

Ste*_*yer 28

您可以使用hasOwnProperty方法来检查这一点

> localStorage.setItem('foo', 123)
undefined
> localStorage.hasOwnProperty('foo')
true
> localStorage.hasOwnProperty('bar')
false
Run Code Online (Sandbox Code Playgroud)

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

  • @FlavienVolken但是你不能拥有存储的`null`值.你可以使用"null",但是那里的代码不会出现错误,而这个代码将在`length`键上失败. (7认同)
  • 这应该是公认的答案.被接受者将认为存储的"空"值未设置,这是错误的. (2认同)
  • @Kaiido你是对的,我有这种行为是因为我直接解析存储的数据并且作为`JSON.parse("null") === JSON.parse(null)`我发生了冲突。 (2认同)
  • 得到了以下ESLint错误:“不要从目标object.eslint(no-prototype-builtins)访问Object.prototype方法'hasOwnProperty'” (2认同)

Vla*_*lav 18

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

var sValue = localStorage['my.token'] || ''; /* for strings */
var iValue = localStorage['my.token'] || 0; /* for integers */
Run Code Online (Sandbox Code Playgroud)


Vik*_*ari 8

有几种方法可以检查我在这里添加它们

方法一

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

方法二

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

方法三

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

方法4

if(localStorage.hasOwnProperty("infiniteScrollEnabled")){
     console.log("Item exists in localstorage");
 }else{
    console.log("Item does not exist in localstoarge";
 }
Run Code Online (Sandbox Code Playgroud)


Dee*_*mas 6

if(!localStorage.hash) localStorage.hash = "thinkdj";
Run Code Online (Sandbox Code Playgroud)

或者

var secret =  localStorage.hash || 42;
Run Code Online (Sandbox Code Playgroud)


Ayu*_*ary 5

可以尝试这样的事情:

 let x = localStorage.getItem('infiniteScrollEnabled') === null ? "not found" : localStorage.getItem('infiniteScrollEnabled')
Run Code Online (Sandbox Code Playgroud)