HTML5 LocalStorage:检查密钥是否存在

Gab*_*iel 120 javascript html5 local-storage cordova

为什么这不起作用?

if(typeof(localStorage.getItem("username"))=='undefined'){
    alert('no');
};
Run Code Online (Sandbox Code Playgroud)

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

这是一个ios phonegap应用程序.

Ult*_*nct 268

引用规范:

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

你应该实际检查null.

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

  • `null`的typeof是``null'`,而不是`null`(希望我有意义). (14认同)
  • @Gabriel:删除`typeof(..)`.再次检查我的答案. (3认同)
  • 谢谢,这是我的第一个错误!但它也不能用if(typeof(localStorage.getItem("username"))=== null){alert('no')}; (2认同)

小智 35

这个方法对我有用:

if ("username" in localStorage) {
    alert('yes');
} else {
    alert('no');
}
Run Code Online (Sandbox Code Playgroud)

  • 此解决方案对诸如“length”之类的键给出了误报。接受的答案是解决这个问题的正确方法。 (7认同)

Der*_*rin 16

更新:

if (localStorage.hasOwnProperty("username")) {
    //
}
Run Code Online (Sandbox Code Playgroud)

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

if (localStorage["username"]) {
    //
}
Run Code Online (Sandbox Code Playgroud)

  • 不完全 - 它是`if(localStorage ["username"] == undefined || localStorage ["username"] == 0 || localStorage ["username"] == null || localStorage ["username"] =的缩写= false || localStorage ["username"] =='')`@ AllanRuin (8认同)
  • 它是`if(localStorage["username"]==undefined)`的缩写 (2认同)
  • @oriadam不完全; 你们都倒退了.它是`if(localStorage ["username"]的缩写!== undefined && localStorage ["username"]!== 0 && localStorage ["username"]!== null && localStorage ["username"]!== false &&的localStorage [ "用户名"]!== '')` (2认同)

Que*_*tin 13

MDN文档显示了如何将getItem方法implementated:

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

如果未设置该值,则返回null.您正在测试是否存在undefined.检查是否null相反.

if(localStorage.getItem("username") === null){
Run Code Online (Sandbox Code Playgroud)