为什么这不起作用?
if(typeof(localStorage.getItem("username"))=='undefined'){
    alert('no');
};
目标是将用户从索引页面重定向到登录页面(如果尚未登录)。这里的localStorage.getItem("username"))变量暂时没有定义。
这是一个 ios phonegap 应用程序。
为什么这不起作用?
if(typeof(localStorage.getItem("username"))=='undefined'){
    alert('no');
};
目标是将用户从索引页面重定向到登录页面(如果尚未登录)。这里的localStorage.getItem("username"))变量暂时没有定义。
这是一个 ios phonegap 应用程序。
引用规范:
getItem(key) 方法必须返回与给定键关联的当前值。如果与对象关联的列表中不存在给定键,则此方法必须返回 null。
您实际上应该检查null.
if (localStorage.getItem("username") === null) {
  //...
}
    这种方法对我有用:
if ("username" in localStorage) {
    alert('yes');
} else {
    alert('no');
}
    更新:
if (localStorage.hasOwnProperty("username")) {
    //
}
另一种方式,当值不期望为空字符串、null 或任何其他虚假值时相关:
if (localStorage["username"]) {
    //
}
    MDN 文档显示了该方法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){