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)
小智 35
这个方法对我有用:
if ("username" in localStorage) {
alert('yes');
} else {
alert('no');
}
Run Code Online (Sandbox Code Playgroud)
Der*_*rin 16
更新:
if (localStorage.hasOwnProperty("username")) {
//
}
Run Code Online (Sandbox Code Playgroud)
另一种方式,当值不是空字符串,null或任何其他虚假值时相关:
if (localStorage["username"]) {
//
}
Run Code Online (Sandbox Code Playgroud)
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)
归档时间: |
|
查看次数: |
187668 次 |
最近记录: |