2

如何检查本地存储值是否为空?例如..

localStorage.setItem('favoriteflavor','');

var taste = localStorage.getItem('favoriteflavor');

if(taste == null){
   console.log('favoriteflavor is null');
} 
else {
   console.log('favoriteflavor is NOT null');
}

这是最有意义的,但我没有得到任何结果。这个我也试过了。。

 if(localStorage['favoriteflavor'] == 'null'){ 
   console.log('favoriteflavor is null');
 }

http://jsfiddle.net/AwsyE/6/

4

2 回答 2

4

如果您设置favoriteflavor为空字符串,那么您应该检查它是否为空字符串而不是其他内容

localStorage.setItem('favoriteflavor','');
var taste = localStorage.getItem('favoriteflavor');
if(taste == ''){
   console.log('favoriteflavor is empty');    
}
else{
   console.log('favoriteflavor is NOT empty');
}

或者,如果您要删除favoriteflavor,那么您可以对照 null 检查它

localStorage.setItem('favoriteflavor','chocolate');
delete localStorage['favoriteflavor'];
// or use localStorage.removeItem('favoriteflavor');

var taste = localStorage.getItem('favoriteflavor');

if(taste == null){

   console.log('favoriteflavor is null');

}
else
{
   console.log('favoriteflavor is NOT null');
}

http://jsfiddle.net/mowglisanu/AwsyE/10/

于 2012-11-16T19:27:33.523 回答
0

您在此处将您的项目设置为“”:

localStorage.setItem('favoritefla','');

并测试输出是否为 == null

if(localStorage['favoriteflavor'] == 'null'

当它等于 '' 因为你自己之前已经设置了这个值。

我相信您正在尝试了解浏览器是否有localStorage容量,您可以通过测试是否可以从该对象中插入和删除项目来做到这一点,如下所示:

var hasStorage = (function() {
  try {
    localStorage.setItem(mod, mod);
    localStorage.removeItem(mod);
    return true;
  } catch(e) {
    return false;
  }
}());

如果浏览器具有 localStorage 容量,上述函数将返回 true。希望对你有帮助,加油

于 2012-11-16T19:28:39.903 回答