[英]js variable is undefined but if-statement never true
有没有其他方法可以检查未定义? 因为下面的变量local.Retrieved的console.log告诉我它是未定义的,但是我的IF语句不是真的...
Screen.prototype.getModulesPrototype = function() {
var self = this;
console.log('Retrieve modules content from local storage (if present)');
var locallyRetrieved = localStorage.getItem('modulesPrototype');
console.log('locallyRetrieved: '+locallyRetrieved);
if( typeof(locallyRetrieved) =='undefined' || locallyRetrieved == null ) {
console.log('nothing found in localStorage so go online to fetch it');
var remotelyRetrieved = self.getModuleAjax();
localStorage.setItem('modulesPrototype', remotelyRetrieved);
locallyRetrieved = localStorage.getItem('modulesPrototype');
}
啊,以为我找到了。
localStorage.getItem()实际上返回一个字符串“ undefined”,因此可以正常工作
if ( locallyRetrieved == 'undefined' )
好奇...
http://underscorejs.org/#isUndefined请查看此链接以检查未定义的条件
使用localStorage.getItem()
您只需检查响应是否为true。 因此,您应该能够检查:
if( locallyRetrieved ) {
// do stuff
}
看到这个小提琴: http : //jsfiddle.net/3kC3Z/2/
规范指定如果未找到任何内容,则getItem
应该返回null:
“如果给定的键在与对象关联的列表中不存在,则此方法必须返回null。”
尝试这个
if(locallyRetrieved ==undefined || locallyRetrieved == null ) {
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.