Html HTML5 LocalStorage:检查密钥是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16010827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 07:33:31  来源:igfitidea点击:

HTML5 LocalStorage: Checking if a key exists

javascripthtmlcordovalocal-storage

提问by Gabriel

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.

目标是将用户从索引页面重定向到登录页面(如果尚未登录)。这里localStorage.getItem("username"))暂时没有定义变量。

It's for an ios phonegap app.

它适用于 ios phonegap 应用程序。

回答by UltraInstinct

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.

getItem(key) 方法必须返回与给定键关联的当前值。如果给定的键在与对象关联的列表中不存在,则此方法必须返回 null。

You should actually check against null.

您实际上应该检查null.

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

回答by user3332298

This method worked for me:

这种方法对我有用:

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

回答by Derin

Update:

更新:

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

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

另一种方式,当 value 不是空字符串、null 或任何其他虚假值时相关:

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

回答by Quentin

The MDN documentationshows how the getItemmethod is implementated:

MDN文档显示了如何getItem方法是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 nullinstead.

如果未设置该值,则返回null。您正在测试它是否是undefined。检查它是否是null

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