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

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/

最佳答案

如果将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/

10-05 21:12