为什么这个不起作用?
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) {
//...
}
null
的类型是 "null"
,不是 null
(希望我说得清楚)。 - georgtypeof(..)
。请再次检查我的答案。 - UltraInstinctCREATE 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)
。 - Hans这种方法对我有效:
if ("username" in localStorage) {
alert('yes');
} else {
alert('no');
}
length
等关键字产生错误的正面结果。被接受的答案是解决这个问题的正确方式。 - kamoroso94localStorage.__proto__
,您将看到可能会发生冲突的属性。 - rob更新:
if (localStorage.hasOwnProperty("username")) {
//
}
当值不期望为空字符串、null或任何其他假值时,另一种相关的方法:
if (localStorage["username"]) {
//
}
if( localStorage["username"]==undefined )
的缩写。 - Allan Ruinif (localStorage["username"]==undefined || localStorage["username"]==0 || localStorage["username"]==null || localStorage["username"]==false || localStorage["username"]=='')
的缩写。@AllanRuin - oriadamif (localStorage["username"]!==undefined && localStorage["username"]!==0 && localStorage["username"]!==null && localStorage["username"]!==false && localStorage["username"]!=='')
。 - JoL根据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){
typeof
与 null 进行比较。你需要比较实际的值。 - Quentin==
而不是 ===
,因为(出于某种奇怪的原因)null == undefined
是 true。再说了,你什么都不需要,就像 @Derin 回答的那样,你可以简单地写成 if (localStorage["username"])
。 - oriadam
localStorage['username']='admin'
然后操纵你的网站。 - oriadam