【问题标题】:HTML5 LocalStorage: Checking if a key exists [duplicate]HTML5 LocalStorage:检查密钥是否存在[重复]
【发布时间】:2013-04-07 07:27:06
【问题描述】:

为什么这不起作用?

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

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

这是一个 ios phonegap 应用程序。

【问题讨论】:

  • 我很惊讶还没有人说 - 客户端安全性非常不鼓励。可以直接按 F12 并运行 localStorage['username']='admin' 然后搞乱你的网站。
  • @oriadam 我希望没有人将授权基于localStorage,但是将JWT accessToken存储在localStorage中是完全可以的。

标签: javascript html cordova local-storage


【解决方案1】:

这个方法对我有用:

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

【讨论】:

  • 在我看来,这是最好的选择,因为它可以区分一个值是否已设置以及它是否可能是假/假。
  • 此解决方案会为 length 之类的键提供误报。接受的答案是解决此问题的正确方法。
【解决方案2】:

更新:

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

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

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

【讨论】:

  • if( localStorage["username"]==undefined )的简称
  • 不完全-它是if (localStorage["username"]==undefined || localStorage["username"]==0 || localStorage["username"]==null || localStorage["username"]==false || localStorage["username"]=='')@AllanRuin 的缩写
  • @oriadam 不完全;你们俩都弄反了。 if (localStorage["username"]!==undefined && localStorage["username"]!==0 && localStorage["username"]!==null && localStorage["username"]!==false && localStorage["username"]!=='')的缩写
  • @JoL 哈哈,你是对的 :) 我正在更新答案
  • 这个方法看起来更好,因为它只是检查键而不不必要地返回键值,例如 if (localStorage.getItem(key) === null)
【解决方案3】:

引用specification:

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

您实际上应该检查null

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

【讨论】:

  • 谢谢,这是我的第一个错误!但它也不适用于 if(typeof(localStorage.getItem("username"))===null){ alert('no') };
  • null 的类型是 "null",而不是 null(希望我说得通)。
  • @Gabriel:删除typeof(..)。再次检查我的答案。
  • 值得注意的是,FF (28.0) 对其 localStorage 表施加的约束允许空值:CREATE TABLE webappsstore2 (scope TEXT, key TEXT, value TEXT, secure INTEGER, owner TEXT) 而 Chrome 不允许:CREATE TABLE ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB NOT NULL ON CONFLICT FAIL)
  • @Derin 不,如果“用户名”确实存在,但存储的值为 false 怎么办?
【解决方案4】:

MDN documentation 显示了getItem 方法是如何实现的:

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

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

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

【讨论】:

  • 好的,我在上面回答了 Thrustmaster。但这并不能更好地工作:/
  • @Gabriel — 在您上面的评论中,您将typeof 的值与空值进行比较。您需要比较实际值。
  • 或者使用== 而不是=== 因为(出于某种奇怪的原因)null==undefined 是真的。再说一次,你不需要任何东西,就像@Derin 回答的那样,你可以简单地if (localStorage["username"])
猜你喜欢
  • 2017-12-26
  • 2012-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-10
  • 2015-06-07
  • 2014-09-14
相关资源
最近更新 更多