HTML5 LocalStorage: Checking if a key exists [dupl

2019-01-30 17:05发布

问题:

This question already has an answer here:

  • How to check whether a Storage item is set? 9 answers

Why this does not work ?

if(typeof(localStorage.getItem("username"))=='undefined'){
    alert('no');
};

The goal is to redirect the user from the index page to the login page if not already logged. Here the localStorage.getItem("username")) variable is not defined for the moment.

It's for an ios phonegap app.

回答1:

Quoting from the specification:

The getItem(key) method must return the current value associated with the given key. If the given key does not exist in the list associated with the object then this method must return null.

You should actually check against null.

if (localStorage.getItem("username") === null) {
  //...
}


回答2:

This method work for me:

if("username" in localStorage){
    alert('yes');
} else {
   alert('no');
}


回答3:

Update:

if (localStorage.hasOwnProperty("username")) {
    //
}

Another way, relevant when value is not expected to be empty string, null or any other falsy value:

if (localStorage["username"]) {
    //
}


回答4:

The MDN documentation shows how the getItem method is implementated:

Object.defineProperty(oStorage, "getItem", {
      value: function (sKey) { return sKey ? this[sKey] : null; },
      writable: false,
      configurable: false,
      enumerable: false
    });

If the value isn't set, it returns null. You are testing to see if it is undefined. Check to see if it is null instead.

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